- font-style
- Try it
- Syntax
- Values
- Variable fonts
- Accessibility concerns
- Formal definition
- Formal syntax
- Examples
- Font styles
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- 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
- Значения и примеры использования
- Font-family
- Font-style
- Font-variant
- Font-weight
- Font-size
- Line-height
- Наследование
- Нюансы
- Чем заменить свойство font
- Материалы по теме
font-style
The font-style CSS property sets whether a font should be styled with a normal, italic, or oblique face from its font-family .
Try it
Italic font faces are generally cursive in nature, usually using less horizontal space than their unstyled counterparts, while oblique faces are usually just sloped versions of the regular face. When the specified style is not available, both italic and oblique faces are simulated by artificially sloping the glyphs of the regular face (use font-synthesis to control this behavior).
Syntax
font-style: normal; font-style: italic; font-style: oblique; font-style: oblique 10deg; /* Global values */ font-style: inherit; font-style: initial; font-style: revert; font-style: revert-layer; font-style: unset;
The font-style property is specified as a single keyword chosen from the list of values below, which can optionally include an angle if the keyword is oblique .
Values
Selects a font that is classified as normal within a font-family .
Selects a font that is classified as italic . If no italic version of the face is available, one classified as oblique is used instead. If neither is available, the style is artificially simulated.
Selects a font that is classified as oblique . If no oblique version of the face is available, one classified as italic is used instead. If neither is available, the style is artificially simulated.
Selects a font classified as oblique , and additionally specifies an angle for the slant of the text. If one or more oblique faces are available in the chosen font family, the one that most closely matches the specified angle is chosen. If no oblique faces are available, the browser will synthesize an oblique version of the font by slanting a normal face by the specified amount. Valid values are degree values of -90deg to 90deg inclusive. If an angle is not specified, an angle of 14 degrees is used. Positive values are slanted to the end of the line, while negative values are slanted towards the beginning.
In general, for a requested angle of 14 degrees or greater, larger angles are preferred; otherwise, smaller angles are preferred (see the spec’s font matching section for the precise algorithm).
Variable fonts
Variable fonts can offer a fine control over the degree to which an oblique face is slanted. You can select this using the modifier for the oblique keyword.
For TrueType or OpenType variable fonts, the «slnt» variation is used to implement varying slant angles for oblique, and the «ital» variation with a value of 1 is used to implement italic values. See font-variation-settings .
Note: For the example below to work, you’ll need a browser that supports the CSS Fonts Level 4 syntax in which font-style: oblique can accept an . The demo loads with font-style: oblique 23deg; . Change the value to see the slant of the text change.
Accessibility concerns
Large sections of text set with a font-style value of italic may be difficult for people with cognitive concerns such as Dyslexia to read.
Formal definition
Initial value | normal |
---|---|
Applies to | all elements. It also applies to ::first-letter and ::first-line . |
Inherited | yes |
Computed value | as specified |
Animation type | by computed value type; normal animates as oblique 0deg |
Formal syntax
Examples
Font styles
p class="normal">This paragraph is normal.p> p class="italic">This paragraph is italic.p> p class="oblique">This paragraph is oblique.p>
.normal font-style: normal; > .italic font-style: italic; > .oblique font-style: oblique; >
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Feb 21, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.
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
Свойство 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 .
Материалы по теме
«Доктайп» — журнал о фронтенде. Читайте, слушайте и учитесь с нами.