Перейти к содержимому

Как сменить шрифт в mozilla

  • автор:

Веб-шрифты

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

Предварительные требования: Основная компьютерная грамотность, основы HTML (изучите Введение в HTML), основы CSS (изучите Введение в CSS), Основы CSS текста и шрифта.
Задача: Изучить как применять веб-шрифты к веб-странице, использовать сторонний сервис или писать код самостоятельно.

Краткое повторение семейств шрифтов

Как мы рассматривали в Фундаментальной стилизации текста и шрифта, шрифты применённые к вашему HTML могут контролироваться при помощи свойства font-family . Оно принимает одно и более имён семейств шрифтов и браузер следует по списку пока не найдёт тот шрифт, который является доступным в системе, под управлением которой он работает:

p  font-family: Helvetica, "Trebuchet MS", Verdana, sans-serif; > 

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

Веб-шрифты

Но есть альтернатива, которая работает очень хорошо начиная с 6-ой версии IE. Веб-шрифты — это функция CSS позволяющая вам указывать файлы шрифтов, загружаемые вместе с вашим веб-сайтом по мере доступа к нему, это означает, что любой браузер, поддерживающий веб-шрифты, может иметь в своём распоряжении именно те шрифты, которые вы укажете. Замечательно! Требуемый синтаксис выглядит примерно так:

Во-первых, у вас есть блок @font-face в начале CSS, который указывает файл(-ы) шрифтов для загрузки:

@font-face  font-family: "myFont"; src: url("myFont.woff"); > 

Ниже вы можете использовать имя семейства шрифтов, указанное внутри @font-face, чтобы применить свой собственный шрифт ко всему, что вам нравится, как обычно:

html  font-family: "myFont", "Bitstream Vera Serif", serif; > 

Синтаксис становится немного сложнее, чем этот; мы вдадимся в подробности ниже.

Есть две важные вещи, которые нужно иметь в виду о веб-шрифтах:

  1. Браузеры поддерживают разные форматы шрифтов, поэтому вам будут нужны несколько форматов шрифтов для приличной кросс-браузерной поддержки. Например, большинство современных браузеров поддерживают WOFF/WOFF2 (Web Open Font Format versions 1 and 2), наиболее эффективный формат, но старые версии IE поддерживают только шрифты EOT (Embedded Open Type) и вам возможно понадобиться включать версию SVG шрифта для поддержки старых версий браузеров iPhone и Android. Ниже мы покажем вам как генерировать требуемый код.
  2. В основном шрифты не бесплатны для использования. Вы должны платить за них и/или соблюдать другие условия лицензии такие как указание создателя шрифта в коде (или на вашем сайте). Вы не должны красть шрифты и использовать их без должного указания авторства.

Примечание: Веб-шрифты как технология поддерживается в Internet Explorer начиная с 4 версии!

Активное изучение: пример веб-шрифта

Имея это в виду, давайте создадим базовый пример веб-шрифта из первых принципов. Сложно продемонстрировать это на встроенном живом примере, поэтому вместо, мы бы хотели, чтобы следовали детальным шагам в секциях ниже, чтобы понять идею процесса

Вы должны использовать файлы web-font-start.html и web-font-start.css как отправную точку добавляя в них ваш код (см. живой пример). Сейчас сделайте копию этих файлов в новой директории на вашем компьютере. В файле web-font-start.css вы найдёте некоторый минимальный CSS для работы с базовым макетом и вёрсткой примера.

Поиск шрифтов

В этом примере мы будем использовать два веб-шрифта, один для заголовков, и другой для основного текста. Для того чтобы начать нам необходимо найти файлы шрифтов, которые содержат эти шрифты. Шрифты созданы шрифтовыми «цехами» и хранятся в разных форматах фалов. Как правило существует три типа сайтов, где вы можете получить шрифты:

  • Бесплатный дистрибьютер шрифтов: это сайт, который предоставляет бесплатные шрифты для скачивания (могут существовать некоторые условия лицензии, например, указание создателя шрифта). Примеры включают Font Squirrel, dafont, и Everything Fonts.
  • Платный дистрибьютер шрифтов: это сайт, который предоставляет шрифты за плату, например fonts.com или myfonts.com. Также вы можете купить шрифты напрямую у производителя шрифтов, например Linotype, Monotype, или Exljbris.
  • Сервис онлайн шрифтов: это сайт, который предоставляет вам шрифты, делая весь процесс проще. Смотрите раздел Использование онлайн-сервиса шрифтов для более подробной информации.

Давайте найдём какие-нибудь шрифты! Отправляйтесь на Font Squirrel и выберите два шрифта — симпатичный интересный шрифт для заголовков (может быть симпатично выглядящий или шрифт с засечками) и немного менее кричащий и более читабельный шрифт для параграфов. Когда вы найдёте каждый шрифт, нажмите на кнопку загрузки и сохраните файлы в той же директории, где ранее вы сохранили файлы HTML и CSS. Не имеет значения являются ли они TTF (True Type Fonts) или OTF (Open Type Fonts).

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

Примечание: В разделе «Find fonts» в колонке справа, вы можете кликать по различным тегам и классификациям чтобы отфильтровать отображаемые варианты для выбора.

Генерация требуемого кода

Теперь вам надо будет сгенерировать требуемый код (и форматы шрифтов). Для каждого шрифта проделайте следующие шаги.

  1. Убедитесь, что вы выполнили все лицензионные требования если вы собираетесь использовать это в коммерческих и/или веб проектах.
  2. Перейдите на Fontsquirrel Webfont Generator.
  3. Выгрузите два ваших файла шрифтов используя кнопку Upload Fonts.
  4. Поставьте галочку отмеченную «Yes, the fonts I’m uploading are legally eligible for web embedding».
  5. Кликните по Download your kit.

После того как генератор закончит обработку, вы должны получить ZIP файл к загрузке — сохраните его в той же директории что и ваши HTML и CSS.

Реализация кода в вашем демо

Теперь распакуйте набор веб-шрифта, который вы только что сгенерировали. Внутри распакованной папки вы увидите три полезных элемента:

  • несколько версий каждого шрифта (например .ttf , .woff , .woff2 и т.д.; предоставленные шрифты будут обновляться со временем по мере изменения требований поддержки браузера). Как упомянуто выше, несколько шрифтов нужны для кросс-браузерной поддержки — это метод Fontsquirrel быть уверенными что вы получили всё что вам надо.
  • Демо файл HTML для каждого шрифта — загрузите их в ваш браузер чтобы посмотреть, как будет выглядеть шрифт в разных контекстах использования.
  • Файл stylesheet.css , который содержит сгенерированный @font-face код который вам нужен.

Для внедрения их в ваше демо следуйте следующим шагам:

  1. Переименуйте распакованную папку на что-нибудь лёгкое и простое, например fonts .
  2. Откройте файл stylesheet.css и скопируйте содержимое обоих @font-face блоков в ваш файл web-font-start.css — вам надо вставить их в самый верх, до любого вашего CSS, так как шрифты должны быть импортированы до того, как вы сможете использовать их на вашем сайте.
  3. Каждый из функций url() указывает на файл шрифта который мы хотим импортировать в наш CSS — мы должны убедиться в том, что пути к файлам верные, поэтому добавьте fonts/ в начало каждого пути (настройте так как необходимо).
  4. Теперь вы можете использовать эти шрифты в ваших стеках шрифтов, как и любой веб-безопасный или по умолчанию системный шрифт. Например:
font-family: "zantrokeregular", serif; 

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

Примечание: Если у вас возникли какие-либо проблемы с тем что что-то не работает, смело сравнивайте файлы вашей версии с нашей законченной — см. web-font-finished.html и web-font-finished.css (run the finished example live).

Использование онлайн-сервиса шрифтов

Онлайн-сервисы шрифтов обычно хранят и обслуживают шрифты для вас, поэтому вам не надо переживать о написании @font-face кода и обычно необходимо просто вставить строчку или две простого кода в ваш сайт для того чтобы все работало. Примеры включают Adobe Fonts и Cloud.typography. Большинство из этих услуг на основе подписки, за исключением Google Fonts, полезный бесплатный сервис, особенно для быстрого тестирования работы и написания демо.

Большинство из этих сервисов легки в использовании, поэтому мы не будем освещать их в деталях. Давайте кратко рассмотрим Google fonts, чтобы вы понимали идею. И снова, используйте копии web-font-start.html и web-font-start.css в качестве отправной точки.

  1. Отправляйтесь на Google Fonts.
  2. Используйте фильтры с правой стороны чтобы отобразить типы шрифтов, которые вы хотите выбрать и выберите пару шрифтов, которые вам понравятся.
  3. Для выбора семейства шрифтов нажмите на кнопку ⊕ рядом с ним.
  4. Когда вы выбрали семейства шрифтов, нажмите на панель [Number] Families Selected в низу страницы.
  5. На полученном экране, сначала вам надо скопировать строку показанного HTML кода и вставить её в head вашего HTML файла. Вставьте его выше существующего элемента для того, чтоб шрифт импортировался до того, как вы начнёте пользоваться им в вашем CSS.
  6. Далее вам надо скопировать CSS-объявления, перечисленные в вашем CSS, чтобы применить пользовательские шрифты к вашему HTML.

Примечание: вы можете найти законченные версии google-font.html и google-font.css, если вам необходимо сверить вашу работу с нашей (см. live).

@font-face более детально

Давайте исследуем тот @font-face синтаксис, который fontsquirrel сгенерировал для вас. Это то, как выглядит один из этих блоков:

@font-face  font-family: "ciclefina"; src: url("fonts/cicle_fina-webfont.eot"); src: url("fonts/cicle_fina-webfont.eot?#iefix") format("embedded-opentype"), url("fonts/cicle_fina-webfont.woff2") format("woff2"), url("fonts/cicle_fina-webfont.woff") format("woff"), url("fonts/cicle_fina-webfont.ttf") format("truetype"), url("fonts/cicle_fina-webfont.svg#ciclefina") format("svg"); font-weight: normal; font-style: normal; > 

Это называется «пуленепробиваемым @font-face синтаксисом», после публикации Пола Айриша (Paul Irish), с самого начала, когда @font-face начал получать популярность (Bulletproof @font-face Syntax). Давайте пройдёмся по нему, чтобы посмотреть, что он делает:

  • font-family : В этой строке указывается имя, которое вы хотите использовать для обозначения шрифта. Вы можете указать его как угодно, если вы используете его последовательно в вашем CSS.
  • src : В этой строке указывается путь к файлам шрифтов которые будут импортированы в ваш CSS ( url путь) и формат каждого файла шрифта ( format часть). Последняя часть в каждом случае опциональна, но полезно объявлять его, потому что это позволяет браузерам быстрее находить шрифт, который они могут использовать. Могут быть перечислены несколько объявлений, разделённых запятыми — браузер будет искать среди них и использовать первый который найдёт и тот который он понимает — поэтому лучше всего ставить новые, лучшие форматы такие как WOFF2 в начало, а старые, не такие хорошие форматы как TTF в конец. Единственное исключение это EOT шрифты — они размещены первыми чтобы исправить пару багов в старых версиях IE который постарается использовать первую вещь, которую найдёт, даже если он не умеет использовать этот шрифт.
  • font-weight / font-style : В этих строках указывается какую толщину имеет шрифт и является ли он курсивом или нет. Если вы импортируете несколько значений толщины одного и того же шрифта вы можете указать какая у них толщина/стиль и затем использовать разные значения font-weight / font-style для выбора между ними, вместо того, чтобы называть всех разных членов семейства шрифтов разными именами. @font-face совет: установите font-weight и font-style так чтобы ваш CSS был простым от Роджера Джонсона (Roger Johansson) покажет, что делать более детально.

Примечание: вы также можете указать определённые значения font-variant (en-US) и font-stretch (en-US) для ваших веб-шрифтов. В новых браузерах вы также можете указать значение unicode-range (en-US), который является конкретным диапазоном символов, которые вы хотите использовать из веб-шрифта — в поддерживающих браузерах, будут загружены только указанные символы, сохраняя от ненужной загрузки. Creating Custom Font Stacks with Unicode-Range от Drew McLellan предоставляет некоторые полезные идеи того как это использовать

Переменные шрифты

В браузерах доступна новая технология, называемая переменными шрифтами — это шрифты, которые позволяют включить в единственный файл много разных вариантов дизайнов шрифтов, вместо того чтобы иметь отдельные файлы шрифтов для каждой ширины, толщины или стиля. Они несколько продвинуты для нашего курса для начинающих, но если вы хотите расширить свои знания и посмотреть на них, прочитайте наше Руководство по переменным шрифтам (en-US) .

Испытайте свои навыки!

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

Заключение

Теперь, когда вы ознакомились с нашими статьями об основах стилизации текста, пришло время проверить ваше понимание нашей оценкой модуля «Задание: стилизация школьного сайта».

В этом модуле

  • Фундаментальная стилизация текста и шрифта
  • Стилизация списков
  • Стилизация ссылок
  • Веб-шрифты
  • Задание: Стилизация школьного сайта

Found a content problem with this page?

  • Edit the page on GitHub.
  • Report the content issue.
  • View the source on GitHub.

This page was last modified on 3 авг. 2023 г. by MDN contributors.

Your blueprint for a better internet.

Основы стилизирования текста и шрифта

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

Необходимые знания: Базовые компьютерные знания, Основы HTML (раздел Введение в HTML), основы CSS (раздел Введение в CSS).
Задача: Изучить основные свойства и техники, необходимые для стилизации текста на веб-страницах.

Что участвует в стилизации текста в CSS?

Как вы уже проверили в своей работе с HTML и CSS, текст внутри элемента выкладывается в поле содержимого элемента. Он начинается в левом верхнем углу области содержимого (или в правом верхнем углу, в случае содержимого языка RTL) и течёт к концу строки. Как только он достигает конца, он переходит к следующей строке и продолжает, затем к следующей строке, пока все содержимое не будет помещено в коробку. Текстовое содержимое эффективно ведёт себя как ряд встроенных элементов, размещённых на соседних строках и не создающих разрывы строк до тех пор, пока не будет достигнут конец строки, или если вы не принудите разрыв строки вручную с помощью элемента .

Примечание: если приведённый выше абзац оставляет вас в замешательстве, то не имеет значения — вернитесь и просмотрите нашу статью о модели коробки, чтобы освежить теорию модели коробки, прежде чем продолжить.

Свойства CSS, используемые для стилизации текста, обычно делятся на две категории, которые мы рассмотрим отдельно в этой статье:

  • Font styles: Свойства, влияющие на шрифт, применяемый к тексту, влияющие на то, какой шрифт применяется, насколько он велик, является ли он полужирным, курсивным и т. д.
  • Text layout styles: Свойства, влияющие на интервал и другие особенности компоновки текста, позволяющие манипулировать, например, пространством между строками и буквами, а также тем, как текст выравнивается в поле содержимого.

Примечание: имейте в виду, что текст внутри элемента все затронуты как одна единая сущность. Вы не можете выбирать и стилизовать подразделы текста, если вы не обернёте их в соответствующий элемент (например, или ), или использовать текстовый псевдоэлемент, такой как ::first-letter (выделяет первую букву текста элемента). first-line (выделяет первую строку текста элемента) или ::selection (выделяет текст, выделенный в данный момент курсором.)

Шрифты

Давайте сразу перейдём к рассмотрению свойств для стилизации шрифтов. В этом примере мы применим некоторые различные свойства CSS к одному и тому же образцу HTML, который выглядит следующим образом:

h1>Tommy the cath1> p>Well I remember it as though it were a meal ago. p> p> Said Tommy the Cat as he reeled back to clear whatever foreign matter may have nestled its way into his mighty throat. Many a fat alley rat had met its demise while staring point blank down the cavernous barrel of this awesome prowling machine. Truly a wonder of nature this urban predator — Tommy the cat had many a story to tell. But it was a rare occasion such as this that he did. p> 

Color

The color (en-US) property sets the color of the foreground content of the selected elements (which is usually the text, but can also include a couple of other things, such as an underline or overline placed on text using the text-decoration (en-US) property).

color can accept any CSS color unit, for example:

p  color: red; > 

This will cause the paragraphs to become red, rather than the standard browser default black, like so:

h1>Tommy the cath1> p>Well I remember it as though it were a meal ago. p> p> Said Tommy the Cat as he reeled back to clear whatever foreign matter may have nestled its way into his mighty throat. Many a fat alley rat had met its demise while staring point blank down the cavernous barrel of this awesome prowling machine. Truly a wonder of nature this urban predator — Tommy the cat had many a story to tell. But it was a rare occasion such as this that he did. p> 

Font families

To set a different font on your text, you use the font-family property — this allows you to specify a font (or list of fonts) for the browser to apply to the selected elements. The browser will only apply a font if it is available on the machine the website is being accessed on; if not, it will just use a browser default font. A simple example looks like so:

p  font-family: arial; > 

This would make all paragraphs on a page adopt the arial font, which is found on any computer.

Web safe fonts

Speaking of font availability, there are only a certain number of fonts that are generally available across all systems and can therefore be used without much worry. These are the so-called web safe fonts.

Most of the time, as web developers we want to have more specific control over the fonts used to display our text content. The problem is to find a way to know which font is available on the computer used to see our web pages. There is no way to know this in every case, but the web safe fonts are known to be available on nearly all instances of the most used operating systems (Windows, macOS, the most common Linux distributions, Android, and iOS).

The list of actual web safe fonts will change as operating systems evolve, but it’s reasonable to consider the following fonts web safe, at least for now (many of them have been popularized thanks to the Microsoft Core fonts for the Web initiative in the late 90s and early 2000s):

Name Generic type Notes
Arial sans-serif It’s often considered best practice to also add Helvetica as a preferred alternative to Arial as, although their font faces are almost identical, Helvetica is considered to have a nicer shape, even if Arial is more broadly available.
Courier New monospace Some OSes have an alternative (possibly older) version of the Courier New font called Courier. It’s considered best practice to use both with Courier New as the preferred alternative.
Georgia serif
Times New Roman serif Some OSes have an alternative (possibly older) version of the Times New Roman font called Times. It’s considered best practice to use both with Times New Roman as the preferred alternative.
Trebuchet MS sans-serif You should be careful with using this font — it isn’t widely available on mobile OSes.
Verdana sans-serif

Примечание: Among various resources, the cssfontstack.com website maintains a list of web safe fonts available on Windows and macOS operating systems, which can help you make your decision about what you consider safe for your usage.

Примечание: There is a way to download a custom font along with a webpage, to allow you to customize your font usage in any way you want: web fonts. This is a little bit more complex, and we will be discussing this in a separate article later on in the module.

Default fonts

CSS defines five generic names for fonts: serif , sans-serif , monospace , cursive and fantasy . Those are very generic and the exact font face used when using those generic names is up to each browser and can vary for each operating system they are running on. It represents a worst case scenario where the browser will try to do its best to provide at least a font that looks appropriate. serif , sans-serif and monospace are quite predictable and should provide something reasonable. On the other hand, cursive and fantasy are less predictable and we recommend using them very carefully, testing as you go.

The five names are defined as follows:

Term Definition Example
serif Fonts that have serifs (the flourishes and other small details you see at the ends of the strokes in some typefaces) My big red elephant
sans-serif Fonts that don’t have serifs. My big red elephant
monospace Fonts where every character has the same width, typically used in code listings. My big red elephant
cursive Fonts that are intended to emulate handwriting, with flowing, connected strokes. My big red elephant
fantasy Fonts that are intended to be decorative. My big red elephant
Font stacks

Since you can’t guarantee the availability of the fonts you want to use on your webpages (even a web font could fail for some reason), you can supply a font stack so that the browser has multiple fonts it can choose from. This simply involves a font-family value consisting of multiple font names separated by commas, e.g.

p  font-family: "Trebuchet MS", Verdana, sans-serif; > 

In such a case, the browser starts at the beginning of the list and looks to see if that font is available on the machine. If it is, it applies that font to the selected elements. If not, it moves on to the next font, and so on.

It is a good idea to provide a suitable generic font name at the end of the stack so that if none of the listed fonts are available, the browser can at least provide something approximately suitable. To emphasise this point, paragraphs are given the browser’s default serif font if no other option is available — which is usually Times New Roman — this is no good for a sans-serif font!

Примечание: Font names that have more than one word — like Trebuchet MS — need to be surrounded by quotes, for example «Trebuchet MS» .

A font-family example

Let’s add to our previous example, giving the paragraphs a sans-serif font:

p  color: red; font-family: Helvetica, Arial, sans-serif; > 

This gives us the following result:

h1>Tommy the cath1> p>Well I remember it as though it were a meal ago. p> p> Said Tommy the Cat as he reeled back to clear whatever foreign matter may have nestled its way into his mighty throat. Many a fat alley rat had met its demise while staring point blank down the cavernous barrel of this awesome prowling machine. Truly a wonder of nature this urban predator — Tommy the cat had many a story to tell. But it was a rare occasion such as this that he did. p> 

Font size

In our previous module’s CSS values and units article, we reviewed length and size units. Font size (set with the font-size property) can take values measured in most of these units (and others, such as percentages), however the most common units you’ll use to size text are:

  • px (pixels): The number of pixels high you want the text to be. This is an absolute unit — it results in the same final computed value for the font on the page in pretty much any situation.
  • em s: 1 em is equal to the font size set on the parent element of the current element we are styling (more specifically, the width of a capital letter M contained inside the parent element.) This can become tricky to work out if you have a lot of nested elements with different font sizes set, but it is doable, as you’ll see below. Why bother? It is quite natural once you get used to it, and you can use em to size everything, not just text. You can have an entire website sized using em , which makes maintenance easy.
  • rem s: These work just like em , except that 1 rem is equal to the font size set on the root element of the document (i.e. ), not the parent element. This makes doing the maths to work out your font sizes much easier, although if you want to support really old browsers, you might struggle — rem is not supported in Internet Explorer 8 and below.

The font-size of an element is inherited from that element’s parent element. This all starts with the root element of the entire document — — the font-size of which is set to 16 px as standard across browsers. Any paragraph (or another element that doesn’t have a different size set by the browser) inside the root element will have a final size of 16 px . Other elements may have different default sizes, for example an (en-US) element has a size of 2 em set by default, so it will have a final size of 32 px .

article> p>My paragraphp> article> 

You would need to set its em value to 20/24, or 0.83333333 em . The maths can be complicated, so you need to be careful about how you style things. It is best to use rem where you can, to keep things simple, and avoid setting the font-size of container elements where possible.

A simple sizing example

When sizing your text, it is usually a good idea to set the base font-size of the document to 10 px , so that then the maths is a lot easier to work out — required (r)em values are then the pixel font size divided by 10, not 16. After doing that, you can easily size the different types of text in your document to what you want. It is a good idea to list all your font-size rulesets in a designated area in your stylesheet, so they are easy to find.

Our new result is like so:

h1>Tommy the cath1> p>Well I remember it as though it were a meal ago. p> p> Said Tommy the Cat as he reeled back to clear whatever foreign matter may have nestled its way into his mighty throat. Many a fat alley rat had met its demise while staring point blank down the cavernous barrel of this awesome prowling machine. Truly a wonder of nature this urban predator — Tommy the cat had many a story to tell. But it was a rare occasion such as this that he did. p> 
html  font-size: 10px; > h1  font-size: 5rem; > p  font-size: 1.5rem; color: red; font-family: Helvetica, Arial, sans-serif; > 

Font style, font weight, text transform, and text decoration

CSS provides four common properties to alter the visual weight/emphasis of text:

  • font-style : Used to turn italic text on and off. Possible values are as follows (you’ll rarely use this, unless you want to turn some italic styling off for some reason):
    • normal : Sets the text to the normal font (turns existing italics off.)
    • italic : Sets the text to use the italic version of the font if available; if not available, it will simulate italics with oblique instead.
    • oblique : Sets the text to use a simulated version of an italic font, created by slanting the normal version.
    • normal , bold : Normal and bold font weight
    • lighter , bolder : Sets the current element’s boldness to be one step lighter or heavier than its parent element’s boldness.
    • 100 – 900 : Numeric boldness values that provide finer grained control than the above keywords, if needed.
    • none : Prevents any transformation.
    • uppercase : Transforms all text to capitals.
    • lowercase : Transforms all text to lower case.
    • capitalize : Transforms all words to have the first letter capitalized.
    • full-width : Transforms all glyphs to be written inside a fixed-width square, similar to a monospace font, allowing aligning of e.g. Latin characters along with Asian language glyphs (like Chinese, Japanese, Korean).
    • none : Unsets any text decorations already present.
    • underline : Underlines the text.
    • overline : Gives the text an overline.
    • line-through : Puts a strikethrough over the text .

    Let’s look at adding a couple of these properties to our example:

    Our new result is like so:

    h1>Tommy the cath1> p>Well I remember it as though it were a meal ago. p> p> Said Tommy the Cat as he reeled back to clear whatever foreign matter may have nestled its way into his mighty throat. Many a fat alley rat had met its demise while staring point blank down the cavernous barrel of this awesome prowling machine. Truly a wonder of nature this urban predator — Tommy the cat had many a story to tell. But it was a rare occasion such as this that he did. p> 
    html  font-size: 10px; > h1  font-size: 5rem; text-transform: capitalize; > h1 + p  font-weight: bold; > p  font-size: 1.5rem; color: red; font-family: Helvetica, Arial, sans-serif; > 

    Text drop shadows

    You can apply drop shadows to your text using the text-shadow property. This takes up to four values, as shown in the example below:

    text-shadow: 4px 4px 5px red; 

    The four properties are as follows:

    1. The horizontal offset of the shadow from the original text — this can take most available CSS length and size units, but you’ll most commonly use px ; positive values move the shadow right, and negative values left. This value has to be included.
    2. The vertical offset of the shadow from the original text; behaves basically just like the horizontal offset, except that it moves the shadow up/down, not left/right. This value has to be included.
    3. The blur radius — a higher value means the shadow is dispersed more widely. If this value is not included, it defaults to 0, which means no blur. This can take most available CSS length and size units.
    4. The base color of the shadow, which can take any CSS color unit. If not included, it defaults to black .
    Multiple shadows

    You can apply multiple shadows to the same text by including multiple shadow values separated by commas, for example:

    text-shadow: 1px 1px 1px red, 2px 2px 1px red; 

    If we applied this to the (en-US) element in our Tommy the cat example, we’d end up with this:

    h1>Tommy the cath1> p>Well I remember it as though it were a meal ago. p> p> Said Tommy the Cat as he reeled back to clear whatever foreign matter may have nestled its way into his mighty throat. Many a fat alley rat had met its demise while staring point blank down the cavernous barrel of this awesome prowling machine. Truly a wonder of nature this urban predator — Tommy the cat had many a story to tell. But it was a rare occasion such as this that he did. p> 
    html  font-size: 10px; > h1  font-size: 5rem; text-transform: capitalize; text-shadow: 1px 1px 1px red, 2px 2px 1px red; > h1 + p  font-weight: bold; > p  font-size: 1.5rem; color: red; font-family: Helvetica, Arial, sans-serif; > 

    Примечание: You can see more interesting examples of text-shadow usage in the Sitepoint article Moonlighting with CSS text-shadow.

    Text layout

    With basic font properties out the way, let’s now have a look at properties we can use to affect text layout.

    Text alignment

    The text-align property is used to control how text is aligned within its containing content box. The available values are as follows, and work in pretty much the same way as they do in a regular word processor application:

    • left : Left-justifies the text.
    • right : Right-justifies the text.
    • center : Centers the text.
    • justify : Makes the text spread out, varying the gaps in between the words so that all lines of text are the same width. You need to use this carefully — it can look terrible, especially when applied to a paragraph with lots of long words in it. If you are going to use this, you should also think about using something else along with it, such as hyphens , to break some of the longer words across lines.

    If we applied text-align: center; to the (en-US) in our example, we’d end up with this:

    h1>Tommy the cath1> p>Well I remember it as though it were a meal ago. p> p> Said Tommy the Cat as he reeled back to clear whatever foreign matter may have nestled its way into his mighty throat. Many a fat alley rat had met its demise while staring point blank down the cavernous barrel of this awesome prowling machine. Truly a wonder of nature this urban predator — Tommy the cat had many a story to tell. But it was a rare occasion such as this that he did. p> 
    html  font-size: 10px; > h1  font-size: 5rem; text-transform: capitalize; text-shadow: 1px 1px 1px red, 2px 2px 1px red; text-align: center; > h1 + p  font-weight: bold; > p  font-size: 1.5rem; color: red; font-family: Helvetica, Arial, sans-serif; > 

    Line height

    The line-height property sets the height of each line of text — this can take most length and size units, but can also take a unitless value, which acts as a multiplier and is generally considered the best option — the font-size is multiplied to get the line-height . Body text generally looks nicer and is easier to read when the lines are spaced apart; the recommended line height is around 1.5 – 2 (double spaced.) So to set our lines of text to 1.6 times the height of the font, you’d use this:

    line-height: 1.6; 
    h1>Tommy the cath1> p>Well I remember it as though it were a meal ago. p> p> Said Tommy the Cat as he reeled back to clear whatever foreign matter may have nestled its way into his mighty throat. Many a fat alley rat had met its demise while staring point blank down the cavernous barrel of this awesome prowling machine. Truly a wonder of nature this urban predator — Tommy the cat had many a story to tell. But it was a rare occasion such as this that he did. p> 
    html  font-size: 10px; > h1  font-size: 5rem; text-transform: capitalize; text-shadow: 1px 1px 1px red, 2px 2px 1px red; text-align: center; > h1 + p  font-weight: bold; > p  font-size: 1.5rem; color: red; font-family: Helvetica, Arial, sans-serif; line-height: 1.6; > 

    Letter and word spacing

    The letter-spacing and word-spacing properties allow you to set the spacing between letters and words in your text. You won’t use these very often, but might find a use for them to get a certain look, or to improve the legibility of a particularly dense font. They can take most length and size units.

    So as an example, we could apply some word- and letter-spacing to the first line of each element in our example:

    p::first-line  letter-spacing: 4px; word-spacing: 4px; > 

    Let’s add some to our example, like so:

    h1>Tommy the cath1> p>Well I remember it as though it were a meal ago. p> p> Said Tommy the Cat as he reeled back to clear whatever foreign matter may have nestled its way into his mighty throat. Many a fat alley rat had met its demise while staring point blank down the cavernous barrel of this awesome prowling machine. Truly a wonder of nature this urban predator — Tommy the cat had many a story to tell. But it was a rare occasion such as this that he did. p> 
    html  font-size: 10px; > h1  font-size: 5rem; text-transform: capitalize; text-shadow: 1px 1px 1px red, 2px 2px 1px red; text-align: center; letter-spacing: 2px; > h1 + p  font-weight: bold; > p::first-line  letter-spacing: 4px; word-spacing: 4px; > p  font-size: 1.5rem; color: red; font-family: Helvetica, Arial, sans-serif; line-height: 1.6; letter-spacing: 1px; > 

    Other properties worth looking at

    The above properties give you an idea of how to start styling text on a webpage, but there are many more properties you could use. We just wanted to cover the most important ones here. Once you’ve become used to using the above, you should also explore the following:

    • font-variant (en-US): Switch between small caps and normal font alternatives.
    • font-kerning (en-US): Switch font kerning options on and off.
    • font-feature-settings (en-US): Switch various OpenType font features on and off.
    • font-variant-alternates (en-US): Control the use of alternate glyphs for a given font-face.
    • font-variant-caps (en-US): Control the use of alternate capital glyphs.
    • font-variant-east-asian (en-US): Control the usage of alternate glyphs for East Asian scripts, like Japanese and Chinese.
    • font-variant-ligatures : Control which ligatures and contextual forms are used in text.
    • font-variant-numeric : Control the usage of alternate glyphs for numbers, fractions, and ordinal markers.
    • font-variant-position (en-US): Control the usage of alternate glyphs of smaller sizes positioned as superscript or subscript.
    • font-size-adjust (en-US): Adjust the visual size of the font independently of its actual font size.
    • font-stretch (en-US): Switch between possible alternative stretched versions of a given font.
    • text-underline-position (en-US): Specify the position of underlines set using the text-decoration-line property underline value.
    • text-rendering (en-US): Try to perform some text rendering optimization.

    Text layout styles:

    • text-indent : Specify how much horizontal space should be left before the beginning of the first line of the text content.
    • text-overflow (en-US): Define how overflowed content that is not displayed is signaled to users.
    • white-space : Define how whitespace and associated line breaks inside the element are handled.
    • word-break : Specify whether to break lines within words.
    • direction : Define the text direction (This depends on the language and usually it’s better to let HTML handle that part as it is tied to the text content.)
    • hyphens : Switch on and off hyphenation for supported languages.
    • line-break : Relax or strengthen line breaking for Asian languages.
    • text-align-last : Define how the last line of a block or a line, right before a forced line break, is aligned.
    • text-orientation (en-US): Define the orientation of the text in a line.
    • overflow-wrap : Specify whether or not the browser may break lines within words in order to prevent overflow.
    • writing-mode : Define whether lines of text are laid out horizontally or vertically and the direction in which subsequent lines flow.

    Font shorthand

    Many font properties can also be set through the shorthand property font . These are written in the following order: font-style , font-variant (en-US), font-weight , font-stretch (en-US), font-size , line-height , and font-family .

    Among all those properties, only font-size and font-family are required when using the font shorthand property.

    A forward slash has to be put in between the font-size and line-height properties.

    A full example would look like this:

    font: italic normal bold normal 3em/1.5 Helvetica, Arial, sans-serif; 

    Active learning: Playing with styling text

    In this active learning session, we don’t have any specific exercises for you to do: we’d just like you to have a good play with some font/text layout properties, and see what you can produce! You can either do this using offline HTML/CSS files, or enter your code into the live editable example below.

    If you make a mistake, you can always reset it using the Reset button.

    div class="body-wrapper" style="font-family: 'Open Sans Light',Helvetica,Arial,sans-serif;"> h2>HTML Inputh2> textarea id="code" class="html-input" style="width: 90%;height: 10em;padding: 10px;border: 1px solid #0095dd;"> p>Some sample text for your delightp> textarea> h2>CSS Inputh2> textarea id="code" class="css-input" style="width: 90%;height: 10em;padding: 10px;border: 1px solid #0095dd;"> p < >textarea > h2>Outputh2> div class="output" style="width: 90%;height: 10em;padding: 10px;border: 1px solid #0095dd;">div> div class="controls"> input id="reset" type="button" value="Reset" style="margin: 10px 10px 0 0;" /> div> div> 
    const htmlInput = document.querySelector(".html-input"); const cssInput = document.querySelector(".css-input"); const reset = document.getElementById("reset"); let htmlCode = htmlInput.value; let cssCode = cssInput.value; const output = document.querySelector(".output"); const styleElem = document.createElement("style"); const headElem = document.querySelector("head"); headElem.appendChild(styleElem); function drawOutput()  output.innerHTML = htmlInput.value; styleElem.textContent = cssInput.value; > reset.addEventListener("click", function ()  htmlInput.value = htmlCode; cssInput.value = cssCode; drawOutput(); >); htmlInput.addEventListener("input", drawOutput); cssInput.addEventListener("input", drawOutput); window.addEventListener("load", drawOutput); 

    Test your skills!

    You’ve reached the end of this article, and already did some skill testing in our Active Learning section, but can you remember the most important information going forward? You can find an assessment to verify that you’ve retained this information at the end of the module — see Typesetting a community school homepage.

    This assessment tests all the knowledge discussed in this module, so you might want to read the other articles before moving on to it.

    Summary

    We hoped you enjoyed playing with text in this article! The next article will give you all you need to know about styling HTML lists.

    In this module

    • Fundamental text and font styling
    • Styling lists
    • Styling links
    • Web fonts
    • Typesetting a community school homepage

    Found a content problem with this page?

    • Edit the page on GitHub.
    • Report the content issue.
    • View the source on GitHub.

    This page was last modified on 3 авг. 2023 г. by MDN contributors.

    Your blueprint for a better internet.

    Как изменить шрифты по умолчанию в вашем веб-браузере

    Хотя изменение шрифта в браузере может быть не самой важной проблемой, иногда вносить изменения — это весело. Вот почему мы научим вас изменять шрифт по умолчанию в Google Chrome, Mozilla Firefox и Internet Explorer.

    Примечание: инструкции для Chrome и Firefox должны работать в любой операционной системе. Очевидно, что Internet Explorer работает только в Windows, поэтому эти настройки будут работать только там.

    Изменение шрифта Chrome

    Чтобы изменить шрифт в Google Chrome, вам потребуется доступ к «Настройкам шрифта и языка». Начните с открытия браузера, нажмите на три параллельные линии в правом верхнем углу окна, а затем нажмите «Настройки».

    Прокрутите вниз, пока не дойдете до раздела «Веб-контент» и нажмите «Настроить шрифты».

    Кроме того, вы можете просто ввести chrome: // settings / fonts в свой браузер и нажать «Enter». Теперь вы можете изменить все настройки шрифта.

    При необходимости измените шрифты и нажмите «Готово», затем перезапустите браузер.

    Изменение шрифта Firefox

    Если вы используете Firefox в качестве основного браузера, вы можете редактировать шрифты всего за несколько простых шагов. Начните с нажатия трех горизонтальных полос в правом верхнем углу браузера, затем выберите «Параметры».

    Затем вам нужно будет щелкнуть вкладку «Содержимое» и выбрать шрифт из списка доступных шрифтов в раскрывающемся меню.

    В этом окне вы также можете изменить размер шрифта и цвета. Если вы нажмете кнопку «Дополнительно», вы также сможете изменить следующие настройки.

    Примечание: не забудьте оставить флажок «Разрешить страницам выбирать собственные шрифты», иначе большая часть Интернета будет повреждена. Многие сайты, включая этот, используют значки, которые фактически реализованы как пользовательские шрифты.

    Изменение шрифта Internet Explorer

    Если вы являетесь пользователем IE, вы также можете изменить настройки шрифта в своем браузере, выполнив несколько простых шагов. Начните с нажатия маленькой шестеренки в правом верхнем углу браузера, затем нажмите кнопку «Свойства обозревателя».

    Теперь посмотрите в нижнюю часть всплывающего окна и выберите «Шрифты».

    Теперь вы можете изменить шрифты веб-страницы и обычного текста по своему желанию.

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

    font-family

    CSS-свойство font-family определяет приоритетный список из одного или нескольких названий семейства шрифтов и/или общее имя шрифта для выбранного элемента.

    Интерактивный пример

    Значения разделены запятыми, чтобы указать, что они являются альтернативами. Браузер выберет из списка первый шрифт, который установлен или может быть скачан используя правило @font-face .

    Часто удобно использовать сокращённое свойство font , чтобы задать font-size и другие свойства, которые относятся к шрифту.

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

    Свойство font-family определяет список шрифтов в приоритете от высшего к низшему. Процесс выбора шрифта не останавливается после первого шрифта, найденного в системе пользователя. Скорее, выбор шрифта выполняется по одному символу за раз, поэтому если в доступном шрифте нет глифы для нужного символа, пробуются следующие по списку шрифты. (Однако, это не работает в Internet Explorer 6 и ранее.) Когда шрифт доступен только в некоторых стилях , видах (en-US) или размерах , эти свойства могут так же влиять на выбор шрифта.

    Синтаксис

    /* Имя шрифта и общие семейства шрифтов */ font-family: Gill Sans Extrabold, sans-serif; font-family: "Goudy Bookletter 1911", sans-serif; /* Только общие семейства */ font-family: serif; font-family: sans-serif; font-family: monospace; font-family: cursive; font-family: fantasy; font-family: system-ui; font-family: emoji; font-family: math; font-family: fangsong; /* Глобальные значения */ font-family: inherit; font-family: initial; font-family: unset; 

    Свойство font-family получает список из одного или более семейства шрифтов, разделённые запятыми. Каждое семейство шрифтов определяется как или .

    В приведённом ниже примере перечислены два семейства шрифтов, первое , а второе как :

    font-family: Gill Sans Extrabold, sans-serif; 

    Значения

    Имя семейства шрифтов. К примеру, «Times» и «Helvetica» это семейства шрифтов. Названия семейства шрифтов, которые содержат пробелы, должны быть взяты в кавычки.

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

    Глифы имеют завершающие штрихи, расширяющиеся или сужающиеся концы, или имеют фактически зазубренные окончания. Например, «Lucida Bright», «Lucida Fax», Palatino, «Palatino Linotype», Palladio, «URW Palladio», serif.

    Глифы имеют гладкие окончания. Например, «Open Sans», «Fira Sans», «Lucida Sans», «Lucida Sans Unicode», «Trebuchet MS», «Liberation Sans», «Nimbus Sans L», sans-serif.

    Все глифы имеют одинаковую фиксированную ширину. Например, «Fira Mono», «DejaVu Sans Mono», Menlo, Consolas, «Liberation Mono», Monaco, «Lucida Console», monospace.

    Глифы в курсивных шрифтах обычно имеют либо соединительные штрихи, либо другие рукописные характеристики, отличные от наклонных (italic) шрифтов. Глифы частично или полностью связаны, и результат больше напоминает рукописное перо или кисть, чем печатные буквы. Например, «Brush Script MT», «Brush Script Std», «Lucida Calligraphy», «Lucida Handwriting», «Apple Chancery», cursive.

    Фэнтезийные шрифты — это прежде всего декоративные шрифты, которые содержат игривое представление персонажей. Например, Papyrus, Herculanum, Party LET, Curlz MT, Harrington, fantasy.

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

    Это семейство предназначено для особых стилистических задач представления математики: верхний индекс и нижний индекс, скобки, которые пересекают несколько строк, вложенные выражения и двойные глифы с различными значениями.

    Шрифты, специально предназначенные для отображения эмодзи.

    Особый стиль китайских иероглифов, который является чем-то средним между стилем с засечками Song и курсивным стилем Кай. Этот стиль часто используется для правительственных документов.

    Валидные имена семейства шрифтов

    Имена семейств шрифтов должны быть указаны либо в виде строк в кавычках, либо в виде последовательности одного или нескольких идентификаторов без кавычек. Если имя семейства шрифтов содержит цифры или знаки пунктуации, такое имя должно быть заключено в кавычки.

    Например, следующие объявления являются валидными:

    font-family: Gill Sans Extrabold, sans-serif; font-family: "Goudy Bookletter 1911", sans-serif; 

    Следующие объявления являются не валидными:

    font-family: Goudy Bookletter 1911, sans-serif; font-family: Red/Black, sans-serif; font-family: "Lucida" Grande, sans-serif; font-family: Ahem!, sans-serif; font-family: test @foo, sans-serif; font-family: #POUND, sans-serif; font-family: Hawaii 5-0, sans-serif; 

    Формальный синтаксис

    font-family =
    [ (en-US) | (en-US) (en-US) ] (en-US) # (en-US)

    Примеры

    Некоторые общие семейства шрифтов

    .serif  font-family: Times, Times New Roman, Georgia, serif; > .sansserif  font-family: Verdana, Arial, Helvetica, sans-serif; > .monospace  font-family: Lucida Console, Courier, monospace; > .cursive  font-family: cursive; > .fantasy  font-family: fantasy; > .emoji  font-family: emoji; > .math  font-family: math; > .fangsong  font-family: fangsong; > 
    div class="serif">This is an example of a serif font.div> div class="sansserif">This is an example of a sans-serif font.div> div class="monospace">This is an example of a monospace font.div> div class="cursive">This is an example of a cursive font.div> div class="fantasy">This is an example of a fantasy font.div> div class="math">This is an example of a math font.div> div class="emoji">This is an example of an emoji font.div> div class="fangsong">This is an example of a fangsong font.div> 

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

    Specification
    CSS Fonts Module Level 4
    # generic-font-families
    CSS Fonts Module Level 4
    # font-family-prop
    Начальное значение зависит от браузера
    Применяется к all elements and text. Это также применяется к ::first-letter и ::first-line .
    Наследуется да
    Обработка значения как указано
    Animation type discrete

    Совместимость с браузерами

    BCD tables only load in the browser

    [1] system-ui в данный момент не реализовано, смотри баг 1226042.

    [2] system-ui реализовано в Safari (wkbug.com/151493), возможно будет выпущено в ближайшем времени.

    [3] префиксный алиас -apple-system поддерживается в Safari, начиная с OS X 10.11 и iOS 9, а также в Firefox 43 на macOS (баг 1201318).

    Found a content problem with this page?

    • Edit the page on GitHub.
    • Report the content issue.
    • View the source on GitHub.

    This page was last modified on 7 авг. 2023 г. by MDN contributors.

    Your blueprint for a better internet.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *