Title of the document

Содержание
  1. CSS font-size Property
  2. Syntax
  3. Example of the font-size property:
  4. Result
  5. Usage of percentage values
  6. Example of the font-size property specified in percentage:
  7. Usage of the em unit
  8. Example of the font-size property with the «em» value:
  9. Usage of the rem unit
  10. Example of the font-size property with the «rem» value:
  11. Usage of the ex unit
  12. Usage of viewport units
  13. Example of the font-size property with the «length» value:
  14. Example of the font-size property with the absolute-size values:
  15. Example of the font-size property with «smaller» and «larger» values:
  16. Values
  17. Browser support
  18. CSS Font Size
  19. Set Font Size With Pixels
  20. Example
  21. Set Font Size With Em
  22. Example
  23. Use a Combination of Percent and Em
  24. Example
  25. Responsive Font Size
  26. Hello World
  27. Example
  28. 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 Определяет размер шрифта элемента. Размер может быть установлен несколькими способами. Набор констант ( xx-small , x-small , small , medium , large , x-large , xx-large ) задаёт размер, который называется абсолютным. По правде говоря, они не совсем абсолютны, поскольку зависят от настроек браузера и операционной системы. Другой набор констант ( larger , smaller ) устанавливает относительные размеры шрифта. Поскольку размер унаследован от родительского элемента, эти относительные размеры применяются к родительскому элементу, чтобы определить размер шрифта текущего элемента. В конечном итоге, размер шрифта сильно зависит от значения свойства font-size у родителя элемента. Сам размер шрифта определяется как высота от базовой линии до верхней границы кегельной площадки, как показано на рис. 1. Краткая информация Синтаксис Синтаксис Описание Пример Указывает тип значения.A && B Значения должны выводиться в указанном порядке. && A | B Указывает, что надо выбрать только одно значение из предложенных (A или B). normal | small-caps A || B Каждое значение может использоваться самостоятельно или совместно с другими в произвольном порядке. width || count [ ] Группирует значения. [ crop || cross ] * Повторять ноль или больше раз. [,]* + Повторять один или больше раз. + ? Указанный тип, слово или группа не является обязательным. inset? Повторять не менее A, но не более B раз.# Повторять один или больше раз через запятую. # Значения Для задания абсолютного размера используются следующие значения: 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% берётся размер шрифта родительского элемента. Отрицательные значения не допускаются. Песочница Винни-Пух был всегда не прочь немного подкрепиться, в особенности часов в одиннадцать утра, потому что в это время завтрак уже давно окончился, а обед ещё и не думал начинаться. И, конечно, он страшно обрадовался, увидев, что Кролик достаёт чашки и тарелки. Пример Амазонская низменность Для гостей открываются погреба Прибалатонских винодельческих хозяйств, известных отличными сортами вин «Олазрислинг» и «Сюркебарат». Результат данного примера показан на рис. 1. Рис. 2. Применение свойства font-size Объектная модель Спецификация Спецификация Статус CSS Fonts Module Level 3 Возможная рекомендация CSS Transitions Рабочий проект CSS Level 2 (Revision 1) Рекомендация CSS Level 1 Рекомендация Спецификация Каждая спецификация проходит несколько стадий одобрения. Recommendation ( Рекомендация ) — спецификация одобрена W3C и рекомендована как стандарт. Candidate Recommendation ( Возможная рекомендация ) — группа, отвечающая за стандарт, удовлетворена, как он соответствует своим целям, но требуется помощь сообщества разработчиков по реализации стандарта. Proposed Recommendation ( Предлагаемая рекомендация ) — на этом этапе документ представлен на рассмотрение Консультативного совета W3C для окончательного утверждения. Working Draft ( Рабочий проект ) — более зрелая версия черновика после обсуждения и внесения поправок для рассмотрения сообществом. Editor’s draft ( Редакторский черновик ) — черновая версия стандарта после внесения правок редакторами проекта. Draft ( Черновик спецификации ) — первая черновая версия стандарта. Браузеры В таблице браузеров применяются следующие обозначения. — элемент полностью поддерживается браузером; — элемент браузером не воспринимается и игнорируется; — при работе возможно появление различных ошибок, либо элемент поддерживается с оговорками. Число указывает версию браузреа, начиная с которой элемент поддерживается. См. также Источник
  29. font-size
  30. Краткая информация
  31. Синтаксис
  32. Значения
  33. Песочница
  34. Пример
  35. Амазонская низменность
  36. Объектная модель
  37. Спецификация
  38. Браузеры
  39. См. также

CSS font-size Property

The font-size property defines the font size of the text.

Font size can be defined by the following ways:

Absolute font size includes the following values:

Relative font size includes the following values:

Читайте также:  Responsive Menu

Lengths can be relative lengths (em, ex, px) and absolute lengths (in, cm, mm, pt, pc). Percentages specify an absolute font size relative to the font size of the parent element.

Initial Value medium
Applies to All elements. It also applies to ::first-letter and ::first-line.
Inherited Yes.
Animatable Yes.
Version CSS1
DOM Syntax object.style.fontSize = «15px»;

Syntax

font-size: medium | xx-small | x-small | small | large | x-large | xx-large | smaller | larger | length | initial | inherit;

Example of the font-size property:

html> html> head> title>Title of the document title> style> h1 < font-size: 24pt; > h3 < font-size: 26px; > p < font-size: 1em; > a < font-size: 100%; > span < font-size: x-small; > style> head> body> span>This span is written with x-small value. span> p>This paragraph is written with 1em font-size. p> a href="https://www.w3docs.com/">This hyperlink is written with 100% font-size. a> h3>We used x-small font size for this heading. h3> h1>We set the font size 24pt for this heading. h1> body> html>

Result

CSS font-size Property

Usage of percentage values

Percentage values are relative to the font-size of the parent element. The code below shows its usage:

Example of the font-size property specified in percentage:

html> html>    body> h3>We used x-small font size for this heading.h3> span>This span is written with x-small value.span> p>This paragraph is written with 1em font-size.p> body> html>

Usage of the em unit

The em unit is considered to be a relative unit. It is based on the calculated value of its parent element’s font size. In the code below, the paragraph will be 32px, because 2×16=32, and the heading will have a font-size of 48px because 3×16=48px. This method is very useful because we can be sure that all the child elements will always be relative to each other.

Example of the font-size property with the «em» value:

html> html> head> title>Title of the document title> style> .container < font-size: 16px; > p < font-size: 2em; > h2 < font-size: 3em; > style> head> body> div class="container"> h2>Here is the heading h2> p>Here is the text. p> div> body> html>

Usage of the rem unit

In the case of using the rem unit, the font-size depends on the value of the HTML element. In the example below, the rem unit is inherited from the HTML element, that’s why it is equal to 24px. So, the heading will have a font-size of 24px, because 1.5×16=24px.

Example of the font-size property with the «rem» value:

html> html> head> title>Title of the document title> style> html < font-size: 16px; > h2 < font-size: 1.5rem; > style> head> body> div class="container"> h2>Here is the heading h2> p>Here is the text. p> div> body> html>

Usage of the ex unit

In the case of the ex unit, 1ex is equal to the calculated height of the HTML element’s letter x. In the code example below, the HTML element is 15px. The x-height of that particular font will determine all the other font-sizes.

Usage of viewport units

Viewport units (vw and vh) are used for setting the font-size of an element, which is relative to the size of the viewport.

Example of the font-size property with the «length» value:

html> html> head> title>Title of the document title> style> span < color: green; font-size: 2vh; > p < color: red; font-size: 1em; > .length < color: orange; font-size: 30px; > h3 < color: lightblue; font-size: 3ex; > h1 < color: purple; font-size: 24pt; > a < color: blue; font-size: 120%; > style> head> body> h2>Font-size property h2> span>This text is written with 2vh font-size. span> p>This paragraph is written with 1em font-size. p> div class="length">Example with 30px font-size length div> h3>Example with 3ex font-size length. h3> h1>We set the font size 24pt for this heading. h1> a href="https://www.w3docs.com/">This hyperlink is written with 100% font-size. a> body> html>

Example of the font-size property with the absolute-size values:

html> html> head> title>Title of the document title> style> .font-xxsmall < color: grey; font-size: xx-small; > .font-xsmall < color: grey; font-size: x-small; > .font-small < color: grey; font-size: small; > .fontSize-medium < color: grey; font-size: medium; > .font-large < color: grey; font-size: large; > .font-xlarge < color: grey; font-size: x-large; > .font-xxlarge < color: grey; font-size: xx-large; > style> head> body> h1>Font-size property h1> div class="font-xxsmall">Example with font-size xx-small property div> div class="font-xsmall">Example with font-size x-small property div> div class="font-small">Example with font-size small property div> div class="font-medium">Example with font-size medium property div> div class="font-large">Example with font-size large property div> div class="font-xlarge">Example with font-size x-large property div> div class="font-xxlarge">Example with font-size xx-large property div> body> html>

Example of the font-size property with «smaller» and «larger» values:

html> html> head> title>Title of the document title> style> .smaller < color: red; font-size: smaller; > .larger < color: red; font-size: larger; > style> head> body> h1>font-size property h1> div class="smaller">Example with font-size smaller property div> div class="larger">Example with font-size larger property div> body> html>

Values

Value Description Play it
medium Sets the font-size to medium. This is the default value of this property. Play it »
xx-small Sets the font-size to xx-small. Play it »
x-small Sets the font-size to x-small. Play it »
small Sets the font-size to small. Play it »
large Sets the font-size to large. Play it »
x-large Sets the font-size to x-large. Play it »
xx-large Sets the font-size to xx-large. Play it »
smaller Smallers the font-size. Play it »
larger Largers the font-size. Play it »
length Specifies the font-size by px, em etc. Play it »
% Sets the font-size to a percent of the parent element’s font size. Play it »
initial Makes the property use its default value. Play it »
inherit Inherits the property from its parents element.
Читайте также:  Программирование моделей на java

Browser support

Источник

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

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

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

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

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

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

Краткая информация

Синтаксис

Синтаксис

Описание Пример
Указывает тип значения.
A && B Значения должны выводиться в указанном порядке. &&
A | B Указывает, что надо выбрать только одно значение из предложенных (A или B). normal | small-caps
A || B Каждое значение может использоваться самостоятельно или совместно с другими в произвольном порядке. width || count
[ ] Группирует значения. [ crop || cross ]
* Повторять ноль или больше раз. [,]*
+ Повторять один или больше раз. +
? Указанный тип, слово или группа не является обязательным. inset?
Повторять не менее A, но не более B раз.
# Повторять один или больше раз через запятую. #

Значения

Для задания абсолютного размера используются следующие значения: 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% берётся размер шрифта родительского элемента. Отрицательные значения не допускаются.

Песочница

Винни-Пух был всегда не прочь немного подкрепиться, в особенности часов в одиннадцать утра, потому что в это время завтрак уже давно окончился, а обед ещё и не думал начинаться. И, конечно, он страшно обрадовался, увидев, что Кролик достаёт чашки и тарелки.

Пример

Амазонская низменность

Для гостей открываются погреба Прибалатонских винодельческих хозяйств, известных отличными сортами вин «Олазрислинг» и «Сюркебарат».

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

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

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

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

Спецификация

Спецификация Статус
CSS Fonts Module Level 3 Возможная рекомендация
CSS Transitions Рабочий проект
CSS Level 2 (Revision 1) Рекомендация
CSS Level 1 Рекомендация

Спецификация

Каждая спецификация проходит несколько стадий одобрения.

  • Recommendation ( Рекомендация ) — спецификация одобрена W3C и рекомендована как стандарт.
  • Candidate Recommendation ( Возможная рекомендация ) — группа, отвечающая за стандарт, удовлетворена, как он соответствует своим целям, но требуется помощь сообщества разработчиков по реализации стандарта.
  • Proposed Recommendation ( Предлагаемая рекомендация ) — на этом этапе документ представлен на рассмотрение Консультативного совета W3C для окончательного утверждения.
  • Working Draft ( Рабочий проект ) — более зрелая версия черновика после обсуждения и внесения поправок для рассмотрения сообществом.
  • Editor’s draft ( Редакторский черновик ) — черновая версия стандарта после внесения правок редакторами проекта.
  • Draft ( Черновик спецификации ) — первая черновая версия стандарта.

Браузеры

В таблице браузеров применяются следующие обозначения.

  • — элемент полностью поддерживается браузером;
  • — элемент браузером не воспринимается и игнорируется;
  • — при работе возможно появление различных ошибок, либо элемент поддерживается с оговорками.

Число указывает версию браузреа, начиная с которой элемент поддерживается.

См. также

Источник

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