- Как установить стиль шрифта. CSS-свойство font
- Значения и примеры использования
- Font-family
- Font-style
- Font-variant
- Font-weight
- Font-size
- Line-height
- Наследование
- Нюансы
- Чем заменить свойство font
- Материалы по теме
- CSS Fonts
- Font Selection is Important
- Generic Font Families
- Difference Between Serif and Sans-serif Fonts
- Some Font Examples
- The CSS font-family Property
- Example
- CSS font Property
- Definition and Usage
- Browser Support
- CSS Syntax
- Property Values
- More Examples
- Example
- Related Pages
Как установить стиль шрифта. CSS-свойство font
Свойство font используется для оформления текста на сайте. Оно позволяет задавать различные атрибуты шрифта: размер, начертание, жирность, стиль и цвет.
Свойство в общем виде записывается так:
font-family — устанавливает семейство шрифтов.
font-style — задаёт стиль шрифта.
font-variant — определяет вариант шрифта.
font-weight — задаёт жирность шрифта.
font-size — указывает размер шрифта.
line-height — задаёт высоту строки.
Значения и примеры использования
Font-family
В значении свойства font-family указывается список названий шрифтов, перечисленных через запятую. В начале списка располагают самый желаемый шрифт, затем альтернативный, а в самом конце списка — общий тип шрифта. Браузер проходит по списку слева направо и использует первый найденный в системе или на сайте шрифт.
Font-style
Можно выбрать один из стилей оформления текста: обычный шрифт normal , курсив italic , наклонный oblique .
Font-variant
У свойства font-variant несколько значений:
small-caps — все строчные символы отображаются как заглавные уменьшенного размера.
Font-weight
Насыщенность шрифта можно определить числовым значением от 100 до 900 или ключевым словом, например, обычный шрифт normal , полужирный bold .
Возможные значения font-weight :
- 100: Thin;
- 200: Extra Light (Ultra Light);
- 300: Light;
- 400: Normal;
- 500: Medium;
- 600: Semi Bold (Demi Bold);
- 700: Bold;
- 800: Extra Bold (Ultra Bold);
- 900: Black (Heavy).
Но в большинстве системных шрифтов есть только два варианта толщины: обычный normal (400) и полужирный bold (700).
Font-size
Размер шрифта font-size измеряется в пикселях ( px ), процентах, относительных ( em , rem ) или абсолютных единицах ( pt , cm , mm ).
Абсолютную величину шрифта можно задавать не только в пикселях, пунктах или других величинах, но и особыми ключевыми словами: xx-small , x-small , small , medium , large , x-large и xx-large . Подробно об этих ключевых словах можно узнать в спецификации.
Line-height
Свойство line-height устанавливает высоту строки, указывая множитель относительно размера шрифта. По умолчанию line-height имеет значение normal . Оно указывает браузеру, что межстрочный интервал нужно подобрать автоматически, исходя из размера шрифта.
Наследование
Свойство font наследуется от родительского элемента на его дочерние элементы.
Нюансы
✅ Если заданы различные атрибуты шрифта в разных правилах для одного элемента, последнее применённое свойство переопределит предыдущие.
✅ Если указанное семейство шрифтов не доступно на устройстве пользователя, браузер будет искать и использовать следующий указанный шрифт из списка или использовать шрифт по умолчанию.
⭐ Свойство font поддерживается современными браузерами. Актуальная информация — на caniuse.com.
Чем заменить свойство font
Если нужно управлять отдельными атрибутами шрифта, например, размером, начертанием, жирностью, можно использовать соответствующие отдельные свойства — font-size , font-style и font-weight .
Материалы по теме
«Доктайп» — журнал о фронтенде. Читайте, слушайте и учитесь с нами.
CSS Fonts
Choosing the right font for your website is important!
Font Selection is Important
Choosing the right font has a huge impact on how the readers experience a website.
The right font can create a strong identity for your brand.
Using a font that is easy to read is important. The font adds value to your text. It is also important to choose the correct color and text size for the font.
Generic Font Families
In CSS there are five generic font families:
- Serif fonts have a small stroke at the edges of each letter. They create a sense of formality and elegance.
- Sans-serif fonts have clean lines (no small strokes attached). They create a modern and minimalistic look.
- Monospace fonts — here all the letters have the same fixed width. They create a mechanical look.
- Cursive fonts imitate human handwriting.
- Fantasy fonts are decorative/playful fonts.
All the different font names belong to one of the generic font families.
Difference Between Serif and Sans-serif Fonts
Note: On computer screens, sans-serif fonts are considered easier to read than serif fonts.
Some Font Examples
Generic Font Family | Examples of Font Names |
---|---|
Serif | Times New Roman Georgia Garamond |
Sans-serif | Arial Verdana Helvetica |
Monospace | Courier New Lucida Console Monaco |
Cursive | Brush Script MT Lucida Handwriting |
Fantasy | Copperplate Papyrus |
The CSS font-family Property
In CSS, we use the font-family property to specify the font of a text.
Note: If the font name is more than one word, it must be in quotation marks, like: «Times New Roman».
Tip: The font-family property should hold several font names as a «fallback» system, to ensure maximum compatibility between browsers/operating systems. Start with the font you want, and end with a generic family (to let the browser pick a similar font in the generic family, if no other fonts are available). The font names should be separated with comma. Read more about fallback fonts in the next chapter.
Example
Specify some different fonts for three paragraphs:
.p1 <
font-family: «Times New Roman», Times, serif;
>
.p2 font-family: Arial, Helvetica, sans-serif;
>
.p3 font-family: «Lucida Console», «Courier New», monospace;
>
CSS font Property
Set some font properties with the shorthand declaration:
p.a <
font: 15px Arial, sans-serif;
>
p.b font: italic small-caps bold 12px/30px Georgia, serif;
>
More «Try it Yourself» examples below.
Definition and Usage
The font property is a shorthand property for:
The font-size and font-family values are required. If one of the other values is missing, their default value are used.
Note: The line-height property sets the space between lines.
Default value: | The default value of the font properties |
---|---|
Inherited: | yes |
Animatable: | yes, see individual properties. Read about animatable Try it |
Version: | CSS1 |
JavaScript syntax: | object.style.font=»italic small-caps bold 12px arial,sans-serif» Try it |
Browser Support
The numbers in the table specify the first browser version that fully supports the property.
Note: See individual browser support for each value below.
CSS Syntax
font: font-style font-variant font-weight font-size/line-height font-family|caption|icon|menu|message-box|small-caption|status-bar|initial|inherit;
Property Values
Property/Value | Description | Demo |
---|---|---|
font-style | Specifies the font style. Default value is «normal» | Demo ❯ |
font-variant | Specifies the font variant. Default value is «normal» | Demo ❯ |
font-weight | Specifies the font weight. Default value is «normal» | Demo ❯ |
font-size/line-height | Specifies the font size and the line-height. Default value is «normal» | Demo ❯ |
font-family | Specifies the font family. Default value depends on the browser | Demo ❯ |
caption | Uses the font that are used by captioned controls (like buttons, drop-downs, etc.) | |
icon | Uses the font that are used by icon labels | |
menu | Uses the fonts that are used by dropdown menus | |
message-box | Uses the fonts that are used by dialog boxes | |
small-caption | A smaller version of the caption font | |
status-bar | Uses the fonts that are used by the status bar | |
initial | Sets this property to its default value. Read about initial | |
inherit | Inherits this property from its parent element. Read about inherit |
More Examples
Example
A demonstration of some of the other font property values.
The browser font used in captioned controls.
The browser font used in icon labels.
The browser font used in dropdown menus.
The browser font used in dialog boxes.
A smaller version of the caption font.
The browser font used in the status bar.