font-size

Содержание
  1. CSS Font Size
  2. Set Font Size With Pixels
  3. Example
  4. Set Font Size With Em
  5. Example
  6. Use a Combination of Percent and Em
  7. Example
  8. Responsive Font Size
  9. Hello World
  10. Example
  11. Hello World Viewport is the browser window size. 1vw = 1% of viewport width. If the viewport is 50cm wide, 1vw is 0.5cm. Источник font-size The font-size CSS property sets the size of the font. Changing the font size also updates the sizes of the font size-relative units, such as em , ex , and so forth. Try it Syntax /* values */ font-size : xx-small; font-size : x-small; font-size : small; font-size : medium; font-size : large; font-size : x-large; font-size : xx-large; font-size : xxx-large; /* values */ font-size : smaller; font-size : larger; /* values */ font-size : 12px; font-size : 0.8em; /* values */ font-size : 80%; /* math value */ font-size : math; /* Global values */ font-size : inherit; font-size : initial; font-size : revert; font-size : revert-layer; font-size : unset; The font-size property is specified in one of the following ways: As one of the absolute-size, relative-size or math keywords As a or a , relative to the element’s font size. Values Absolute-size keywords, based on the user’s default font size (which is medium ). Relative-size keywords. The font will be larger or smaller relative to the parent element’s font size, roughly by the ratio used to separate the absolute-size keywords above. For font-relative units that are root-based (such as rem ), the font size is relative to the size of the font used by the (root) element. Note: To maximize accessibility, it is generally best to use values that are relative to the user’s default font size. math Experimental Special mathematical scaling rules must be applied when determining the computed value of the font-size property. Description There are several ways to specify the font size, including keywords or numerical values for pixels or ems. Choose the appropriate method based on the needs of the particular web page. Keywords Pixels Setting the font size in pixel values ( px ) is a good choice when you need pixel accuracy. A px value is static. This is an OS-independent and cross-browser way of literally telling the browsers to render the letters at exactly the number of pixels in height that you specified. The results may vary slightly across browsers, as they may use different algorithms to achieve a similar effect. Font sizing settings can also be used in combination. For example, if a parent element is set to 16px and its child element is set to larger , the child element displays larger than the parent element on the page. Note: Defining font sizes in px is not accessible, because the user cannot change the font size in some browsers. For example, users with limited vision may wish to set the font size much larger than the size chosen by a web designer. Avoid using them for font sizes if you wish to create an inclusive design. Ems Using an em value creates a dynamic or computed font size (historically the em unit was derived from the width of a capital «M» in a given typeface.). The numeric value acts as a multiplier of the font-size property of the element on which it is used. Consider this example: In this case, the font size of elements will be double the computed font-size inherited by elements. By extension, a font-size of 1em equals the computed font-size of the element on which it is used. If a font-size has not been set on any of the ‘s ancestors, then 1em will equal the default browser font-size , which is usually 16px . So, by default 1em is equivalent to 16px , and 2em is equivalent to 32px . If you were to set a font-size of 20px on the element say, then 1em on the elements would instead be equivalent to 20px , and 2em would be equivalent to 40px . In order to calculate the em equivalent for any pixel value required, you can use this formula: em = desired element pixel value / parent element font-size in pixels For example, suppose the font-size of the of the page is set to 16px . If the font-size you want is 12px , then you should specify 0.75em (because 12/16 = 0.75). Similarly, if you want a font size of 10px , then specify 0.625em (10/16 = 0.625); for 22px , specify 1.375em (22/16). The em is a very useful unit in CSS since it automatically adapts its length relative to the font that the reader chooses to use. One important fact to keep in mind: em values compound. Take the following HTML and CSS: html font-size : 100%; > span font-size : 1.6em; > div > span > Outer span > innerspan > outerspan > div > Assuming that the browser’s default font-size is 16px, the words «outer» would be rendered at 25.6px, but the word «inner» would be rendered at 40.96px. This is because the inner ‘s font-size is 1.6em which is relative to its parent’s font-size , which is in turn relative to its parent’s font-size . This is often called compounding. Rems rem values were invented in order to sidestep the compounding problem. rem values are relative to the root html element, not the parent element. In other words, it lets you specify a font size in a relative fashion without being affected by the size of the parent, thereby eliminating compounding. The CSS below is nearly identical to the previous example. The only exception is that the unit has been changed to rem . html font-size : 100%; > span font-size : 1.6rem; > Then we apply this CSS to the same HTML, which looks like this: span > Outer span > innerspan > outerspan > In this example, the words «outer inner outer» are all displayed at 25.6px (assuming that the browser’s font-size has been left at the default value of 16px). Ex Like the em unit, an element’s font-size set using the ex unit is computed or dynamic. It behaves in exactly the same way, except that when setting the font-size property using ex units, the font-size equals the x-height of the first available font used on the page. The number value multiplies the element’s inherited font-size and the font-size compounds relatively. See the W3C Editor’s Draft for a more detailed description of font-relative length units such as ex . Formal definition Initial value medium Applies to all elements. It also applies to ::first-letter and ::first-line . Inherited yes Percentages refer to the parent element’s font size Computed value as specified, but with relative lengths converted into absolute lengths Animation type a length Formal syntax Источник font-size Определяет размер шрифта элемента. Размер может быть установлен несколькими способами. Набор констант ( xx-small , x-small , small , medium , large , x-large , xx-large ) задает размер, который называется абсолютным. По правде говоря, они не совсем абсолютны, поскольку зависят от настроек браузера и операционной системы. Другой набор констант ( larger , smaller ) устанавливает относительные размеры шрифта. Поскольку размер унаследован от родительского элемента, эти относительные размеры применяются к родительскому элементу, чтобы определить размер шрифта текущего элемента. В конечном итоге, размер шрифта сильно зависит от значения свойства font-size у родителя элемента. Сам размер шрифта определяется как высота от базовой линии до верхней границы кегельной площадки, как показано на рис. 1. Синтаксис font-size: абсолютный размер | относительный размер | значение | проценты | inherit Значения Для задания абсолютного размера используются следующие значения: xx-small , x-small , small , medium , large , x-large , xx-large . Их соответствие с размером шрифта в HTML приведено в табл. 1. Табл. 1. Размер шрифта в CSS и HTML CSS xx-small x-small small medium large x-large xx-large HTML 1 2 3 4 5 6 7 Относительный размер шрифта задается значениями larger и smaller . Также разрешается использовать любые допустимые единицы CSS: em (высота шрифта элемента), ex (высота символа х), пункты ( pt ), пикселы ( px ), проценты ( % ) и др. За 100% берется размер шрифта родительского элемента. Отрицательные значения не допускаются. inherit Наследует значение родителя. HTML5 CSS2.1 IE Cr Op Sa Fx

    Duis te feugifacilisi

    Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diem nonummy nibh euismod tincidunt ut lacreet dolore magna aliguam erat volutpat. Ut wisis enim ad minim veniam, quis nostrud exerci tution ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.

    Результат данного примера показан на рис. 1. Рис. 2. Применение свойства font-size Объектная модель [window.]document.getElementById(» elementID «).style.fontSize Браузеры Internet Explorer до версии 7.0 включительно не поддерживает значение inherit . Источник Меняем размер текста CSS-стилями Добавляя на страницы сайта какой-то текст, мы обязательно сталкиваемся с необходимостью оформления текста в соответствии с общим дизайном. Одним из основных параметров, влияющих на читабельность и восприятие текста, является его размер. В этой статье я хочу с вами поговорить о том, как можно изменить размер текста css-свойствами, и какие единицы измерения можно для этого использовать. Навигация по статье: Как изменить размер текста CSS-стилями Для изменения параметров в таблице стилей css существует специализированное свойство font-size, используя которое можно задать размер текста css-стилями в любых, удобных для вас единицах измерения. При этом можно использовать абсолютные и относительные единицу измерения. При указании параметра в абсолютных единицах, его величина не будет меняться относительно значения родительского элемента. К таким единицам измерения относятся: Кроме этого можно использовать ключевые слова: Наиболее распространённой абсолютной единицей измерения шрифта является пиксель (px). Все остальные единицы используются редко, но при желании вы можете использовать и их. При использовании относительных единиц, таких как: %, em, rem, размер шрифта в CSS будет рассчитываться относительно родительского элемента. То есть при изменении шрифта родительского элемента шрифт в блоке будет так же увеличиваться или уменьшаться. Также расчёт размера шрифта может осуществляться относительно ширины или высоты области просмотра. Для этого можно воспользоваться такими единицами измерения как: 1vw – 1% от ширины области просмотра 1vh – 1% от высоты области просмотра 1vmin — 1% от меньшей стороны окна браузера 1vmax — 1% от большей стороны окна браузера Кроме того, так же можно указать размер шрифта CSS ключевым словом в относительном выражении: larger, smaller. При использовании такого CSS-свойства шрифт будет более крупным чем в родительском блоке. При использовании smaller – шрифт будет меньше чем родительском блоке. Как изменить размер текста в HTML Если вам нужно выделить одно слово или фрагмент текста, то, конечно же, это проще всего сделать в html-коде, используя атрибут style. Вот так это будет выглядеть на примере: Источник
  12. font-size
  13. Try it
  14. Syntax
  15. Values
  16. Description
  17. Keywords
  18. Pixels
  19. Ems
  20. Rems
  21. Ex
  22. Formal definition
  23. Formal syntax
  24. font-size
  25. Синтаксис
  26. Значения
  27. Объектная модель
  28. Браузеры
  29. Меняем размер текста CSS-стилями
  30. Навигация по статье:
  31. Как изменить размер текста CSS-стилями
  32. Как изменить размер текста в HTML
Читайте также:  Общая характеристика языка javascript

CSS Font Size

Being able to manage the text size is important in web design. However, you should not use font size adjustments to make paragraphs look like headings, or headings look like paragraphs.

Always use the proper HTML tags, like — for headings and

for paragraphs.

The font-size value can be an absolute, or relative size.

  • Sets the text to a specified size
  • Does not allow a user to change the text size in all browsers (bad for accessibility reasons)
  • Absolute size is useful when the physical size of the output is known
  • Sets the size relative to surrounding elements
  • Allows a user to change the text size in browsers

Note: If you do not specify a font size, the default size for normal text, like paragraphs, is 16px (16px=1em).

Set Font Size With Pixels

Setting the text size with pixels gives you full control over the text size:

Example

Tip: If you use pixels, you can still use the zoom tool to resize the entire page.

Set Font Size With Em

To allow users to resize the text (in the browser menu), many developers use em instead of pixels.

1em is equal to the current font size. The default text size in browsers is 16px. So, the default size of 1em is 16px.

The size can be calculated from pixels to em using this formula: pixels/16=em

Example

h2 font-size: 1.875em; /* 30px/16=1.875em */
>

p font-size: 0.875em; /* 14px/16=0.875em */
>

In the example above, the text size in em is the same as the previous example in pixels. However, with the em size, it is possible to adjust the text size in all browsers.

Unfortunately, there is still a problem with older versions of Internet Explorer. The text becomes larger than it should when made larger, and smaller than it should when made smaller.

Use a Combination of Percent and Em

The solution that works in all browsers, is to set a default font-size in percent for the element:

Example

Our code now works great! It shows the same text size in all browsers, and allows all browsers to zoom or resize the text!

Responsive Font Size

The text size can be set with a vw unit, which means the «viewport width».

That way the text size will follow the size of the browser window:

Hello World

Resize the browser window to see how the font size scales.

Example

Hello World

Viewport is the browser window size. 1vw = 1% of viewport width. If the viewport is 50cm wide, 1vw is 0.5cm.

Источник

font-size

The font-size CSS property sets the size of the font. Changing the font size also updates the sizes of the font size-relative units, such as em , ex , and so forth.

Try it

Syntax

/* values */ font-size: xx-small; font-size: x-small; font-size: small; font-size: medium; font-size: large; font-size: x-large; font-size: xx-large; font-size: xxx-large; /* values */ font-size: smaller; font-size: larger; /* values */ font-size: 12px; font-size: 0.8em; /* values */ font-size: 80%; /* math value */ font-size: math; /* Global values */ font-size: inherit; font-size: initial; font-size: revert; font-size: revert-layer; font-size: unset; 

The font-size property is specified in one of the following ways:

  • As one of the absolute-size, relative-size or math keywords
  • As a or a , relative to the element’s font size.

Values

Absolute-size keywords, based on the user’s default font size (which is medium ).

Relative-size keywords. The font will be larger or smaller relative to the parent element’s font size, roughly by the ratio used to separate the absolute-size keywords above.

For font-relative units that are root-based (such as rem ), the font size is relative to the size of the font used by the (root) element.

Note: To maximize accessibility, it is generally best to use values that are relative to the user’s default font size.

  • math Experimental Special mathematical scaling rules must be applied when determining the computed value of the font-size property.

Description

There are several ways to specify the font size, including keywords or numerical values for pixels or ems. Choose the appropriate method based on the needs of the particular web page.

Keywords

Pixels

Setting the font size in pixel values ( px ) is a good choice when you need pixel accuracy. A px value is static. This is an OS-independent and cross-browser way of literally telling the browsers to render the letters at exactly the number of pixels in height that you specified. The results may vary slightly across browsers, as they may use different algorithms to achieve a similar effect.

Font sizing settings can also be used in combination. For example, if a parent element is set to 16px and its child element is set to larger , the child element displays larger than the parent element on the page.

Note: Defining font sizes in px is not accessible, because the user cannot change the font size in some browsers. For example, users with limited vision may wish to set the font size much larger than the size chosen by a web designer. Avoid using them for font sizes if you wish to create an inclusive design.

Ems

Using an em value creates a dynamic or computed font size (historically the em unit was derived from the width of a capital «M» in a given typeface.). The numeric value acts as a multiplier of the font-size property of the element on which it is used. Consider this example:

In this case, the font size of

elements will be double the computed font-size inherited by

elements. By extension, a font-size of 1em equals the computed font-size of the element on which it is used.

If a font-size has not been set on any of the

‘s ancestors, then 1em will equal the default browser font-size , which is usually 16px . So, by default 1em is equivalent to 16px , and 2em is equivalent to 32px . If you were to set a font-size of 20px on the element say, then 1em on the

elements would instead be equivalent to 20px , and 2em would be equivalent to 40px .

In order to calculate the em equivalent for any pixel value required, you can use this formula:

em = desired element pixel value / parent element font-size in pixels

For example, suppose the font-size of the of the page is set to 16px . If the font-size you want is 12px , then you should specify 0.75em (because 12/16 = 0.75). Similarly, if you want a font size of 10px , then specify 0.625em (10/16 = 0.625); for 22px , specify 1.375em (22/16).

The em is a very useful unit in CSS since it automatically adapts its length relative to the font that the reader chooses to use.

One important fact to keep in mind: em values compound. Take the following HTML and CSS:

html  font-size: 100%; > span  font-size: 1.6em; > 
div> span>Outer span>innerspan> outerspan> div> 

Assuming that the browser’s default font-size is 16px, the words «outer» would be rendered at 25.6px, but the word «inner» would be rendered at 40.96px. This is because the inner ‘s font-size is 1.6em which is relative to its parent’s font-size , which is in turn relative to its parent’s font-size . This is often called compounding.

Rems

rem values were invented in order to sidestep the compounding problem. rem values are relative to the root html element, not the parent element. In other words, it lets you specify a font size in a relative fashion without being affected by the size of the parent, thereby eliminating compounding.

The CSS below is nearly identical to the previous example. The only exception is that the unit has been changed to rem .

html  font-size: 100%; > span  font-size: 1.6rem; > 

Then we apply this CSS to the same HTML, which looks like this:

span>Outer span>innerspan> outerspan> 

In this example, the words «outer inner outer» are all displayed at 25.6px (assuming that the browser’s font-size has been left at the default value of 16px).

Ex

Like the em unit, an element’s font-size set using the ex unit is computed or dynamic. It behaves in exactly the same way, except that when setting the font-size property using ex units, the font-size equals the x-height of the first available font used on the page. The number value multiplies the element’s inherited font-size and the font-size compounds relatively.

See the W3C Editor’s Draft for a more detailed description of font-relative length units such as ex .

Formal definition

Initial value medium
Applies to all elements. It also applies to ::first-letter and ::first-line .
Inherited yes
Percentages refer to the parent element’s font size
Computed value as specified, but with relative lengths converted into absolute lengths
Animation type a length

Formal syntax

Источник

font-size

Определяет размер шрифта элемента. Размер может быть установлен несколькими способами. Набор констант ( xx-small , x-small , small , medium , large , x-large , xx-large ) задает размер, который называется абсолютным. По правде говоря, они не совсем абсолютны, поскольку зависят от настроек браузера и операционной системы.

Другой набор констант ( larger , smaller ) устанавливает относительные размеры шрифта. Поскольку размер унаследован от родительского элемента, эти относительные размеры применяются к родительскому элементу, чтобы определить размер шрифта текущего элемента.

В конечном итоге, размер шрифта сильно зависит от значения свойства font-size у родителя элемента.

Сам размер шрифта определяется как высота от базовой линии до верхней границы кегельной площадки, как показано на рис. 1.

Размер шрифта

Синтаксис

font-size: абсолютный размер | относительный размер | значение | проценты | inherit

Значения

Для задания абсолютного размера используются следующие значения: xx-small , x-small , small , medium , large , x-large , xx-large . Их соответствие с размером шрифта в HTML приведено в табл. 1.

Табл. 1. Размер шрифта в CSS и HTML

CSS xx-small x-small small medium large x-large xx-large
HTML 1 2 3 4 5 6 7

Относительный размер шрифта задается значениями larger и smaller .

Также разрешается использовать любые допустимые единицы CSS: em (высота шрифта элемента), ex (высота символа х), пункты ( pt ), пикселы ( px ), проценты ( % ) и др. За 100% берется размер шрифта родительского элемента. Отрицательные значения не допускаются.

inherit Наследует значение родителя.

HTML5 CSS2.1 IE Cr Op Sa Fx

       

Duis te feugifacilisi

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diem nonummy nibh euismod tincidunt ut lacreet dolore magna aliguam erat volutpat. Ut wisis enim ad minim veniam, quis nostrud exerci tution ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.

Результат данного примера показан на рис. 1.

Применение свойства font-size

Рис. 2. Применение свойства font-size

Объектная модель

[window.]document.getElementById(» elementID «).style.fontSize

Браузеры

Internet Explorer до версии 7.0 включительно не поддерживает значение inherit .

Источник

Меняем размер текста CSS-стилями

размер текста CSS

Добавляя на страницы сайта какой-то текст, мы обязательно сталкиваемся с необходимостью оформления текста в соответствии с общим дизайном. Одним из основных параметров, влияющих на читабельность и восприятие текста, является его размер.

В этой статье я хочу с вами поговорить о том, как можно изменить размер текста css-свойствами, и какие единицы измерения можно для этого использовать.

Как изменить размер текста CSS-стилями

Для изменения параметров в таблице стилей css существует специализированное свойство font-size, используя которое можно задать размер текста css-стилями в любых, удобных для вас единицах измерения. При этом можно использовать абсолютные и относительные единицу измерения.

При указании параметра в абсолютных единицах, его величина не будет меняться относительно значения родительского элемента.

К таким единицам измерения относятся:

Кроме этого можно использовать ключевые слова:

Наиболее распространённой абсолютной единицей измерения шрифта является пиксель (px). Все остальные единицы используются редко, но при желании вы можете использовать и их.

При использовании относительных единиц, таких как: %, em, rem, размер шрифта в CSS будет рассчитываться относительно родительского элемента.

То есть при изменении шрифта родительского элемента шрифт в блоке будет так же увеличиваться или уменьшаться.

Также расчёт размера шрифта может осуществляться относительно ширины или высоты области просмотра.

Для этого можно воспользоваться такими единицами измерения как:

  • 1vw – 1% от ширины области просмотра
  • 1vh – 1% от высоты области просмотра
  • 1vmin — 1% от меньшей стороны окна браузера
  • 1vmax — 1% от большей стороны окна браузера

Кроме того, так же можно указать размер шрифта CSS ключевым словом в относительном выражении: larger, smaller.

При использовании такого CSS-свойства шрифт будет более крупным чем в родительском блоке.

При использовании smaller – шрифт будет меньше чем родительском блоке.

Как изменить размер текста в HTML

Если вам нужно выделить одно слово или фрагмент текста, то, конечно же, это проще всего сделать в html-коде, используя атрибут style.

Вот так это будет выглядеть на примере:

Источник

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