- @font-face
- Синтаксис
- Descriptors
- Formal syntax
- Примеры
- MIME-типы шрифтов
- Примечания
- Спецификации
- Browser compatibility
- See also
- Found a content problem with this page?
- CSS @font-face Rule
- Definition and Usage
- Browser Support
- Syntax
- More Examples
- Example
- CSS Web Fonts
- Different Font Formats
- Browser Support for Font Formats
- Using The Font You Want
- Example
- Using Bold Text
- Example
- CSS Font Descriptors
@font-face
@font-face CSS @-правило (en-US) позволяет указать шрифты для отображения текста на веб-страницах, которые могут быть загружены либо с удалённого сервера, либо с компьютера пользователя. Если в правиле была объявлена функция local() , с названием шрифта, то будет производиться поиск на компьютере пользователя, и в случае обнаружения будет использован этот шрифт. Иначе будет скачан и использован шрифт, указанный в функции url() . @font-face позволяет разрабатывать контент не ограничиваясь набором «безопасных» шрифтов (шрифтов, которые настолько распространены, что считаются доступными по умолчанию). Возможность определить локально установленный шрифт позволяет более гибко настраивать шрифты не полагаясь на соединение с интернетом.Распространённым случаем является одновременное использование url() и local() , чтобы использовать локальный шрифт, если он доступен, или иначе скачать копию шрифта.Это правило может использоваться не только на верхнем уровне CSS, но и внутри любого @-правила (en-US) .
@font-face font-family: "Open Sans"; src: url("/fonts/OpenSans-Regular-webfont.woff2") format("woff2"), url("/fonts/OpenSans-Regular-webfont.woff") format("woff"); >
Синтаксис
Descriptors
Определяет как отображается шрифт, основываясь на том, был ли он загружен и готов ли к использованию.
Указывает имя шрифта, которое будет использоваться для задания свойств шрифта.
Позволяет контролировать другие расширенные особенности OpenType-шрифтов.
Позволяет осуществлять низкоуровневый контроль над вариациями OpenType и TrueType шрифтов, указывая четырёхбуквенные названия осей для изменения вместе с их значениями.
Задаёт ресурс, содержащий данные шрифта. Это может быть URL-адрес расположения удалённого файла шрифта или имя шрифта на компьютере пользователя.
Чтобы дать браузеру возможность выбрать наиболее подходящий формат шрифта, его можно указать при объявлении внутри функции format() : src: url(ideal-sans-serif.woff) format(«woff»), url(basic-sans-serif.ttf) format(«opentype»);Список доступных форматов: «woff» , «woff2» , «truetype» , «opentype» , «embedded-opentype» , и «svg» .
Диапазон Unicode кодов, который будет использоваться в шрифте.
Formal syntax
Примеры
Этот пример просто указывает загружаемый шрифт для использования и применяет его ко всему телу документа:
html> head> title>Web Font Sampletitle> style type="text/css" media="screen, print"> @font-face font-family: "Bitstream Vera Serif Bold"; src: url("https://mdn.github.io/css-examples/web-fonts/VeraSeBd.ttf"); > body font-family: "Bitstream Vera Serif Bold", serif > style> head> body> This is Bitstream Vera Serif Bold. body> html>
В этом примере используется локальный пользовательский шрифт «Helvetica Neue Bold»; если у пользователя этот шрифт не установлен (используются два различных имени), тогда вместо него используется загружаемый шрифт с названием «MgOpenModernaBold.ttf»:
@font-face font-family: MyHelvetica; src: local("Helvetica Neue Bold"), local("HelveticaNeue-Bold"), url(MgOpenModernaBold.ttf); font-weight: bold; >
MIME-типы шрифтов
Формат | MIME-тип |
---|---|
TrueType | font/ttf |
OpenType | font/otf |
Web Open File Format | font/woff |
Web Open File Format 2 | font/woff2 |
Примечания
- Веб шрифты попадают под правило ограничения домена (файлы шрифтов должны находиться на том же самом домене, что и использующая их страница), если это ограничение не снимается с помощью CORS.
- @font-face не может быть объявлен внутри CSS-селектора. Следующий пример не будет работать:
.className @font-face font-family: MyHelvetica; src: local("Helvetica Neue Bold"), local("HelveticaNeue-Bold"), url(MgOpenModernaBold.ttf); font-weight: bold; > >
Спецификации
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on 6 дек. 2022 г. by MDN contributors.
Your blueprint for a better internet.
CSS @font-face Rule
Specify a font named «myFirstFont», and specify the URL where it can be found:
More «Try it Yourself» examples below.
Definition and Usage
With the @font-face rule, web designers do not have to use one of the «web-safe» fonts anymore.
In the @font-face rule you must first define a name for the font (e.g. myFirstFont), and then point to the font file.
To use the font for an HTML element, refer to the name of the font (myFirstFont) through the font-family property:
Browser Support
The @font-face rule is supported in Edge, Chrome, Firefox, Safari, and Opera.
The numbers in the table specifies the first browser version that fully supports the font format.
Font format | |||||
---|---|---|---|---|---|
TTF/OTF | 9.0* | 4.0 | 3.5 | 3.1 | 10.0 |
WOFF | 9.0 | 5.0 | 3.6 | 5.1 | 11.1 |
WOFF2 | 14.0 | 36.0 | 39.0 | 10.0 | 26.0 |
SVG | Not supported | Not supported | Not supported | 3.2 | Not supported |
EOT | 6.0 | Not supported | Not supported | Not supported | Not supported |
*The font format only works when set to be «installable».
Syntax
Font descriptor | Values | Description |
---|---|---|
font-family | name | Required. Defines the name of the font. |
src | URL | Required. Defines the URL(s) where the font should be downloaded from |
font-stretch | normal condensed ultra-condensed extra-condensed semi-condensed expanded semi-expanded extra-expanded ultra-expanded | Optional. Defines how the font should be stretched. Default value is «normal» |
font-style | normal italic oblique | Optional. Defines how the font should be styled. Default value is «normal» |
font-weight | normal bold 100 200 300 400 500 600 700 800 900 | Optional. Defines the boldness of the font. Default value is «normal» |
unicode-range | unicode-range | Optional. Defines the range of unicode characters the font supports. Default value is «U+0-10FFFF» |
More Examples
Example
You must add another @font-face rule containing descriptors for bold text:
The file «sansation_bold.woff» is another font file, that contains the bold characters for the Sansation font.
Browsers will use this whenever a piece of text with the font-family «myFirstFont» should render as bold.
This way you can have many @font-face rules for the same font.
CSS Web Fonts
Web fonts allow Web designers to use fonts that are not installed on the user’s computer.
When you have found/bought the font you wish to use, just include the font file on your web server, and it will be automatically downloaded to the user when needed.
Your «own» fonts are defined within the CSS @font-face rule.
Different Font Formats
TrueType Fonts (TTF)
TrueType is a font standard developed in the late 1980s, by Apple and Microsoft. TrueType is the most common font format for both the Mac OS and Microsoft Windows operating systems.
OpenType Fonts (OTF)
OpenType is a format for scalable computer fonts. It was built on TrueType, and is a registered trademark of Microsoft. OpenType fonts are used commonly today on the major computer platforms.
The Web Open Font Format (WOFF)
WOFF is a font format for use in web pages. It was developed in 2009, and is now a W3C Recommendation. WOFF is essentially OpenType or TrueType with compression and additional metadata. The goal is to support font distribution from a server to a client over a network with bandwidth constraints.
The Web Open Font Format (WOFF 2.0)
TrueType/OpenType font that provides better compression than WOFF 1.0.
SVG Fonts/Shapes
SVG fonts allow SVG to be used as glyphs when displaying text. The SVG 1.1 specification define a font module that allows the creation of fonts within an SVG document. You can also apply CSS to SVG documents, and the @font-face rule can be applied to text in SVG documents.
Embedded OpenType Fonts (EOT)
EOT fonts are a compact form of OpenType fonts designed by Microsoft for use as embedded fonts on web pages.
Browser Support for Font Formats
The numbers in the table specifies the first browser version that fully supports the font format.
Font format | |||||
---|---|---|---|---|---|
TTF/OTF | 9.0* | 4.0 | 3.5 | 3.1 | 10.0 |
WOFF | 9.0 | 5.0 | 3.6 | 5.1 | 11.1 |
WOFF2 | 14.0 | 36.0 | 39.0 | 10.0 | 26.0 |
SVG | Not supported | Not supported | Not supported | 3.2 | Not supported |
EOT | 6.0 | Not supported | Not supported | Not supported | Not supported |
*IE: The font format only works when set to be «installable».
Using The Font You Want
In the @font-face rule; first define a name for the font (e.g. myFirstFont) and then point to the font file.
Tip: Always use lowercase letters for the font URL. Uppercase letters can give unexpected results in IE.
To use the font for an HTML element, refer to the name of the font (myFirstFont) through the font-family property:
Example
@font-face <
font-family: myFirstFont;
src: url(sansation_light.woff);
>
div font-family: myFirstFont;
>
Using Bold Text
You must add another @font-face rule containing descriptors for bold text:
Example
The file «sansation_bold.woff» is another font file, that contains the bold characters for the Sansation font.
Browsers will use this whenever a piece of text with the font-family «myFirstFont» should render as bold.
This way you can have many @font-face rules for the same font.
CSS Font Descriptors
The following table lists all the font descriptors that can be defined inside the @font-face rule:
Descriptor | Values | Description |
---|---|---|
font-family | name | Required. Defines a name for the font |
src | URL | Required. Defines the URL of the font file |
font-stretch | normal condensed ultra-condensed extra-condensed semi-condensed expanded semi-expanded extra-expanded ultra-expanded | Optional. Defines how the font should be stretched. Default is «normal» |
font-style | normal italic oblique | Optional. Defines how the font should be styled. Default is «normal» |
font-weight | normal bold 100 200 300 400 500 600 700 800 900 | Optional. Defines the boldness of the font. Default is «normal» |
unicode-range | unicode-range | Optional. Defines the range of UNICODE characters the font supports. Default is «U+0-10FFFF» |