Javascript css font size

How to Change Font Sizes with JavaScript

Modifying the Font Size of a Web Page Using JavaScript

How to Change Font Sizes with JavaScript

I was asked by a visitor how he could change the font size of a web page using JavaScript. This article shows you one way of doing it.

Prerequisites

Since this question is explicitly about how to do something in JavaScript, I will assume that you have at least a smattering of knowledge about that programming language, or, at the very least, know how to insert JavaScript code into your web page.

You also need some basic knowledge of HTML and CSS.

Changing the Font Size with the Style Property

There are many ways of changing the font size of an element. We will use the simple and direct method of modifying the style property.

Let’s say that you want to change the font size of an element assigned to a variable «x». The JavaScript code for this is essentially:

x.style.fontSize 150%» with the actual font size that you want. Be sure to include the units as well. For example, if you want the text to be 2em, use «2em» instead of «150%». Likewise, if you want the size to be 12 points, specify «12pt». Include the quotation marks.

Changes to the style property are regarded as modifications to the inline style of an element. That is, it’s as though you set a style=»font-size: 150%;» attribute on that HTML tag. As such, it will supersede more general styles that you define in the style sheet.

The example below assumes that you want to change the font size of a specific paragraph. First, do as you normally would if you were only using CSS, by giving that element an identifier, that is, an id . Then change the style.fontSize of that element.

This assumes that the element has «demo» as its id . For example, it was written as »

«.

Demo

If you want to test the above code, click the button below to change the size of the words in this paragraph.

I have coded it so that the button works like a toggle. That is, if you click it a second time, the font will be restored to its original size.

Source Code for the Demo

You can ignore this section. If you only want to use JavaScript to change font sizes, you have all the information you need in the earlier paragraphs. My demo includes extra code to make the button change the font back and forth between two sizes. If you don’t need such functionality, feel free to skip the rest of this article, since that feature adds extra lines to the code that will unnecessarily confuse those new to JavaScript.

Читайте также:  Php display errors ini set display errors

Anyway, for the curious, the JavaScript for the above is as follows:

var tsw_demo_font_is_large = false ;
function tsw_demo_change_font_size( )
demo_paragraph = document.getElementById( ‘demo’ );
if (!tsw_demo_font_is_large) demo_paragraph.style.fontSize = «150%» ;
tsw_demo_font_is_large = true ;
>
else demo_paragraph.style.fontSize = «100%» ;
tsw_demo_font_is_large = false ;
>
>

The paragraph to change is given an id of «demo» to match. That is, it is specified as

. The code for the button merely includes an onclick attribute to invoke the JavaScript function defined earlier.

Since I wanted the button to switch the font back and forth between two sizes, I had to keep track of the current size. This is done using the tsw_demo_font_is_large variable, which is set to false when the page is loaded. It is then updated accordingly each time the button is clicked. (There are, of course, other ways of doing this, but this method is hopefully simple to understand.)

Note that you do not have to follow my example of making the button a toggle. If you want the change to go only in one direction, one solution is to hide the button after it is pressed (the way the hamburger button generated by the Navigation Menu Wizard works; see the demo if you’re interested).

Copyright © 2019 Christopher Heng. All rights reserved.
Get more free tips and articles like this, on web design, promotion, revenue and scripting, from https://www.thesitewizard.com/.

thesitewizard™ News Feed (RSS Site Feed)

Do you find this article useful? You can learn of new articles and scripts that are published on thesitewizard.com by subscribing to the RSS feed. Simply point your RSS feed reader or a browser that supports RSS feeds at https://www.thesitewizard.com/thesitewizard.xml. You can read more about how to subscribe to RSS site feeds from my RSS FAQ.

Please Do Not Reprint This Article

This article is copyrighted. Please do not reproduce or distribute this article in whole or part, in any form.

New Articles

It will appear on your page as:

Copyright © 2019 Christopher Heng. All rights reserved.
thesitewizard™, thefreecountry™ and HowToHaven™ are trademarks of Christopher Heng.
This page was last updated on 29 March 2019.

Источник

Свойства font-size и line-height

Здесь мы рассмотрим, как соотносятся размеры шрифта и строки, и как их правильно задавать.

font-size и line-height

  • font-size – размер шрифта, в частности, определяющий высоту букв.
  • line-height – высота строки.

Для наглядности посмотрим пример HTML, в котором шрифт и размер строки одинаковы:

Размер шрифта font-size – это абстрактное значение, которое привязано к шрифту, и даётся в типографских целях.

Обычно оно равно расстоянию от самой верхней границы букв до самой нижней, исключая «нижние хвосты» букв, таких как p , g . Как видно из примера выше, при размере строки, равном font-size , строка не будет размером точно «под букву».

В зависимости от шрифта, «хвосты» букв при этом могут вылезать, правые буквы Ё и р в примере выше пересекаются как раз поэтому.

В некоторых особо размашистых шрифтах «хвосты букв» могут быть размером с саму букву, а то и больше. Но это, всё же исключение.

Обычно размер строки делают чуть больше, чем шрифт.

По умолчанию в браузерах используется специальное значение line-height:normal .

Оно означает, что браузер может принимать решение о размере строки самостоятельно. Как правило, оно будет в диапазоне 1.1 — 1.25 , но стандарт не гарантирует этого, он говорит лишь, что оно должно быть «разумным» (дословно – англ. reasonable).

Читайте также:  Gamemenu res для css v34

Множитель для line-height

Значение line-height можно указать при помощи px или em , но гораздо лучше – задать его числом.

Значение-число интерпретируется как множитель относительно размера шрифта. Например, значение с множителем line-height: 2 при font-size: 16px будет аналогично line-height: 32px (=16px*2) .

Однако, между множителем и точным значением есть одна существенная разница.

  • Значение, заданное множителем, наследуется и применяется в каждом элементе относительно его размера шрифта. То есть, line-height: 2 означает, что высота строки будет равна удвоенному размеру шрифта, не важно какой шрифт.
  • Значение, заданное в единицах измерения, запоминается и наследуется «как есть». Это означает, что line-height: 32px будет всегда жёстко задавать высоту строки, даже если шрифт во вложенных элементах станет больше или меньше текущего.

Давайте посмотрим, как это выглядит, на примерах:

 
стандартная строка
шрифт в 2 раза больше
шрифт в 2 раза больше

Источник

Style fontSize Property

The fontSize property sets or returns the font size of the text.

Browser Support

Syntax

Return the fontSize property:

Set the fontSize property:

Property Values

Value Description
xx-small
x-small
small
medium
large
x-large
xx-large
Sets the size of the font to different fixed sizes, from xx-small to xx-large
smaller Decreases the font-size by one relative unit
larger Increases the font-size by one relative unit
length Defines the font-size in length units
% Sets the font-size to a % of the parent element’s font size
initial Sets this property to its default value. Read about initial
inherit Inherits this property from its parent element. Read about inherit

Technical Details

Default Value: medium
Return Value: A String, representing the font size of the text in the element
CSS Version CSS1

More Examples

Example

A demonstration of possible values:

var listValue = selectTag.options[selectTag.selectedIndex].text;
document.getElementById(«demo»).style.fontSize = listValue;

Example

Return the font size of an element:

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

How to Change Font Size of HTML Element in JavaScript?

To change the font size of a HTML Element using JavaScript, get reference to this HTML Element element, and assign required font size value to the element.style.fontSize property.

In the following example, we will change the font size of HTML Element with id «myElement» to «25px» , in JavaScript, using element.style.fontSize property.

example.html

Conclusion

In this JavaScript Tutorial, we learned how to change the font size of a HTML Element using JavaScript.

  • How to Change Border Color of HTML Element in JavaScript?
  • How to Change Border Radius of HTML Element in JavaScript?
  • How to Change Border Style of HTML Element in JavaScript?
  • How to Change Border Width of HTML Element in JavaScript?
  • How to Change Bottom Border of HTML Element in JavaScript?
  • How to Change Font Color of HTML Element in JavaScript?
  • How to Change Font Family of HTML Element in JavaScript?
  • How to Change Font Weight of HTML Element in JavaScript?
  • How to Change Height of HTML Element in JavaScript?
  • How to Change Left Border of HTML Element in JavaScript?
  • How to Change Margin of HTML Element in JavaScript?
  • How to Change Opacity of HTML Element in JavaScript?
  • How to Change Padding of HTML Element in JavaScript?
  • How to Change Right Border of HTML Element in JavaScript?
  • How to Change Text in HTML Element to Bold in JavaScript?
  • How to Change Text in HTML Element to Italic in JavaScript?
  • How to Change Top Border of HTML Element in JavaScript?
  • How to Change Width of HTML Element in JavaScript?
  • How to Change the Background Color of HTML Element in JavaScript?
  • How to Change the Border of HTML Element in JavaScript?
  • How to Clear Inline Style of HTML Element in JavaScript?
  • How to Get Children of an HTML Element in JavaScript?
  • How to Get Class Names of an HTML Element as List in JavaScript?
  • How to Get Class Names of an HTML Element as String in JavaScript?
  • How to Get First Child of an HTML Element in JavaScript?
  • How to Get Height of an HTML Element in JavaScript?
  • How to Get Last Child of an HTML Element in JavaScript?
  • How to Get Next Sibling of an HTML Element in JavaScript?
  • How to Get Previous Sibling of an HTML Element in JavaScript?
  • How to Get Width of an HTML Element in JavaScript?
  • How to Hide HTML Element in JavaScript?
  • How to Insert Element in Document after Specific HTML Element using JavaScript?
  • How to Iterate over Children of HTML Element in JavaScript?
  • How to Tag Name of an HTML Element in JavaScript?
  • How to Underline Text in HTML Element in JavaScript?
  • How to get Attributes of HTML Element Element in JavaScript?
  • How to get Number of Child Elements of this HTML Element in JavaScript?
  • JavaScript – Change Style of HTML Element
Читайте также:  Css блок от верхнего края

Источник

Style font Property

The font-size and font-family are required. If one of the other values are missing, the default values will be inserted, if any.

The properties above can also be set with separate style properties. The use of separate properties is highly recommended for non-advanced authors for better controllability.

Browser Support

Syntax

object.style.font = «font-style font-variant font-weight font-size/line-height|caption|icon|menu|
message-box|small-caption|status-bar|initial|inherit;»

Property Values

Value Description
style Sets the font-style
variant Sets the text in a small-caps font
weight Sets the boldness of the font
size Sets the size of the font
lineHeight Sets the distance between lines
family Sets the font face
caption The font used for captioned controls (like buttons, drop-downs, etc.)
icon The font used to label icons
menu The font used in menus
message-box The font used in dialog boxes
small-caption The font used in small controls
status-bar The font used in window status bars
initial Sets this property to its default value. Read about initial
inherit Inherits this property from its parent element. Read about inherit

Technical Details

Default Value: not specified
Return Value: A String, representing different font properties of the element
CSS Version CSS1

More Examples

Example

Return the font of an element:

Источник

Оцените статью