Css font face font size

CSS size-adjust для @font-face

Рассмотрим следующую демонстрацию, где размер шрифта составляет 64 пикселя, а единственное различие между каждым из этих заголовков — это семейство шрифтов. Примеры слева не были скорректированы и имеют несовместимый окончательный размер. В примерах справа используется регулировка размера, чтобы обеспечить постоянный конечный размер 64 пикселя.

В этом примере для отображения высот используются инструменты отладки макета сетки CSS Chrome DevTools.

В этом посте исследуется новый дескриптор шрифтов CSS под названием size-adjust, доступный в Chromium 92 и Firefox 89; (см. caniuse для получения последней поддержки). Он также демонстрирует несколько способов исправить и нормализовать размеры шрифта для более удобного взаимодействия с пользователем, согласованных систем дизайна и более предсказуемого макета страницы. Одним из важных вариантов использования является оптимизация рендеринга веб-шрифтов для предотвращения кумулятивного сдвига макета (CLS).

Frontend-разработчик

Курс «Frontend-разработчик»

— Научитесь верстать сайты для всех типов устройств.

— Сможете использовать JavaScript для работы в браузере.

— 77 часов теории, 346 часов практики.

— Выполните 5 масштабных проектов для портфолио.

— Помощь с поиском работы или стажировки.

Курс веб-разработчик с нуля

Курс «веб-разработчик с нуля»

— Научитесь программировать на JavaScript и PHP.

— Сможете создавать сайты и веб-приложения.

— Сможете уверенно работать и с фронтендом, и с бэкендом веб-сервисов.

— Выполните 9 масштабных проектов для портфолио

— Помощь с поиском работы или стажировки.

PHP-разработчик с нуля

Курс «PHP-разработчик с нуля»

— Научитесь создавать сайты и веб-приложения на языке PHP.

— Изучите актуальные фреймворки Laravel, Simfony и Yii2.

— 78 часов теории и 361 час практики.

— Вы создадите 5 масштабных проектов для портфолио.

— Помощь с поиском работы или стажировки.

Вот интерактивная демонстрация проблемного пространства. Попробуйте изменить шрифт в раскрывающемся списке и обратите внимание:

Разница результатов в высоте.

Смещение визуально раздражающего контента.

Перемещение интерактивных целевых областей (раскрывающийся список прыгает!).

Как масштабировать шрифты с помощью size-adjust

Создаем пользовательский шрифт с именем «Adjusted Typeface».

Использоуем регулировку размера для увеличения каждого глифа до 150% от их размера по умолчанию.

Читайте также:  Показать скрыть блок только css

Влияем только на один импортированный шрифт.

Используйте указанный выше пользовательский шрифт следующим образом:

Предупреждение: Если второй заголовок в приведенной выше демонстрации не больше первого, ваш браузер не поддерживает регулировку размера.

Устранение проблем с CLS с помощью бесшовной замены шрифтов

На следующем видео посмотрите примеры слева и то, как происходит сдвиг при изменении шрифта. Это всего лишь небольшой пример с одним элементом заголовка, и проблема очень заметна.

В примере слева есть сдвиг макета, в правом — нет.

Чтобы улучшить рендеринг шрифтов, можно использовать замену шрифтов. Визуализируйте системный шрифт с быстрой загрузкой, чтобы сначала отобразить контент, а затем замените его веб-шрифтом, когда он завершит загрузку. Это дает вам несколько преимуществ: контент отображается как можно скорее, и вы получаете красиво оформленную страницу, не жертвуя временем пользователя. Однако проблема заключается в том, что иногда, когда загружается веб-шрифт, он сдвигает всю страницу, поскольку имеет немного другой размер поля.

Больше контента означает больший потенциальный сдвиг макета при смене шрифтов

Помещая size-adjust в правило @font-face, устанавливаем глобальную настройку глифа для начертания шрифта. Правильный выбор времени приведет к минимальным визуальным изменениям и беспрепятственному обмену. Чтобы создать плавный обмен, отрегулируйте вручную или попробуйте этот калькулятор регулировки размера от Malte Ubl.

Выберите веб-шрифт Google, затем верните предварительно настроенный фрагмент @font-face.

В начале этого поста проблема с размером шрифта была исправлена методом проб и ошибок. size-adjust увеличивался в исходном коде до тех пор, пока тот же заголовок в Arial не отображал те же 64 пикселя, что и Press Start 2P. Я выровнял два шрифта по целевому размеру шрифта.

Источник

@font-face

The @font-face CSS at-rule specifies a custom font with which to display text; the font can be loaded from either a remote server or a locally-installed font on the user’s own computer.

Syntax

@font-face  font-family: "Trickster"; src: local("Trickster"), url("trickster-COLRv1.otf") format("opentype") tech(color-COLRv1), url("trickster-outline.otf") format("opentype"), url("trickster-outline.woff") format("woff"); > 

Descriptors

Defines the ascent metric for the font.

Defines the descent metric for the font.

Determines how a font face is displayed based on whether and when it is downloaded and ready to use.

Specifies a name that will be used as the font face value for font properties.

A font-stretch value. Accepts two values to specify a range that is supported by a font-face, for example font-stretch: 50% 200%;

A font-style value. Accepts two values to specify a range that is supported by a font-face, for example font-style: oblique 20deg 50deg;

A font-weight value. Accepts two values to specify a range that is supported by a font-face, for example font-weight: 100 400;

Note: The font-variant descriptor was removed from the specification in 2018. The font-variant value property is supported, but there is no descriptor equivalent.

Allows control over advanced typographic features in OpenType fonts.

Allows low-level control over OpenType or TrueType font variations, by specifying the four letter axis names of the features to vary, along with their variation values.

Defines the line gap metric for the font.

Defines a multiplier for glyph outlines and metrics associated with this font. This makes it easier to harmonize the designs of various fonts when rendered at the same font size.

Specifies references to font resources including hints about the font format and technology. It is required for the @font-face rule to be valid.

The range of Unicode code points to be used from the font.

Description

It’s common to use both url() and local() together, so that the user’s installed copy of the font is used if available, falling back to downloading a copy of the font if it’s not found on the user’s device.

If the local() function is provided, specifying a font name to look for on the user’s device, and if the user agent finds a match, that local font is used. Otherwise, the font resource specified using the url() function is downloaded and used.

Browsers attempt to load resources in their list declaration order, so usually local() should be written before url() . Both functions are optional, so a rule block containing only one or more local() without url() is possible. If a more specific fonts with format() or tech() values are desired, these should be listed before versions that don’t have these values, as the less-specific variant would otherwise be tried and used first.

By allowing authors to provide their own fonts, @font-face makes it possible to design content without being limited to the so-called «web-safe» fonts (that is, the fonts which are so common that they’re considered to be universally available). The ability to specify the name of a locally-installed font to look for and use makes it possible to customize the font beyond the basics while making it possible to do so without relying on an internet connection.

Note: Fallback strategies for loading fonts on older browsers are described in the src descriptor page.

The @font-face at-rule may be used not only at the top level of a CSS, but also inside any CSS conditional-group at-rule.

Font MIME Types

Format MIME type
TrueType font/ttf
OpenType font/otf
Web Open Font Format font/woff
Web Open Font Format 2 font/woff2

Notes

  • Web fonts are subject to the same domain restriction (font files must be on the same domain as the page using them), unless HTTP access controls are used to relax this restriction.
  • @font-face cannot be declared within a CSS selector. For example, the following will not work:
.className  @font-face  font-family: "MyHelvetica"; src: local("Helvetica Neue Bold"), local("HelveticaNeue-Bold"), url("MgOpenModernaBold.ttf"); font-weight: bold; > > 

Formal syntax

Examples

Specifying a downloadable font

This example specifies a downloadable font to use, applying it to the entire body of the document:

doctype html> html lang="en-US"> head> meta charset="utf-8" /> meta name="viewport" content="width=device-width" /> title>Web Font Sampletitle> style 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> 

The output of this example code looks like so:

Specifying local font alternatives

In this example, the user’s local copy of «Helvetica Neue Bold» is used; if the user does not have that font installed (both the full font name and the Postscript name are tried), then the downloadable font named «MgOpenModernaBold.ttf» is used instead:

@font-face  font-family: "MyHelvetica"; src: local("Helvetica Neue Bold"), local("HelveticaNeue-Bold"), url("MgOpenModernaBold.ttf"); font-weight: bold; > 

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 Jul 7, 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.

Источник

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