font-weight | htmlbook.ru
Internet Explorer | Chrome | Opera | Safari | Firefox | Android | iOS |
6.0+ | 1.0+ | 3.5+ | 1.0+ | 1.0+ | 1.0+ | 1.0+ |
Краткая информация
Версии CSS
CSS 1 | CSS 2 | CSS 2.1 | CSS 3 |
---|---|---|---|
Описание
Устанавливает насыщенность шрифта. Значение устанавливается от 100 до 900 с шагом 100. Сверхсветлое начертание, которое может отобразить браузер, имеет значение 100, а сверхжирное — 900. Нормальное начертание шрифта (которое установлено по умолчанию) эквивалентно 400, стандартный полужирный текст — значению 700.
Синтаксис
font-weight: bold|bolder|lighter|normal|100|200|300|400|500|600|700|800|900
Значения
Насыщенность шрифта задаётся с помощью ключевых слов: bold — полужирное начертание, normal — нормальное начертание. Также допустимо использовать условные единицы от 100 до 900. Значения bolder и lighter изменяют жирность относительно насыщенности родителя, соответственно, в большую и меньшую сторону.
Пример
HTML5CSS2.1IECrOpSaFx
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>font-weight</title>
<style>
h2 {
font-weight: normal; /* Нормальное начертание */
}
.select {
color: maroon; /* Цвет текста */
font-weight: 600; /* Жирное начертание */
}
</style>
</head>
<body>
<h2>Duis te feugifacilisi</h2>
<p><span>Lorem ipsum dolor sit amet</span>,
consectetuer adipiscing elit, sed diem nonummy nibh euismod tincidunt ut lacreet
dolore magna aliguam erat volutpat. Ut wisis enim ad minim veniam, quis nostrud
exerci tution ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo
consequat.</p>
</body>
</html>
Результат данного примера показан на рис. 1.
Рис. 1. Применение свойства font-weight
Объектная модель
[window.]document.getElementById("elementID").style.fontWeight
Браузеры
Браузеры обычно не могут адекватно показать требуемую насыщенность шрифта, поэтому переключаются между значениями bold, normal и lighter. На практике же начертание в браузерах обычно ограничено всего двумя вариантами: нормальное начертание и жирное начертание.
font-weight - жирный текст | CSS справочник
Поддержка браузерами
12.0+ | 4.0+ | 1.0+ | 2.0+ | 3.5+ | 1.3+ |
Описание
CSS свойство font-weight
позволяет указать, насколько жирным будут выглядеть текст. Как вы знаете, жирный текст выглядит темнее и немного толще, чем обычный. Вы можете использовать жирный текст для любого тега, задав свойству значение bold
.
Если у вас есть элемент, для которого по умолчанию задан жирный шрифт, или он наследует такой шрифт от родительского элемента, то можно уменьшить насыщенность шрифта с помощью значения
.
Для свойства font-weight
предусмотрены также два относительных значения: bolder
и lighter
. Они сделают текст более или менее плотным по сравнению с унаследованным значением. Эти значения используются редко, так как немногие шрифты поддерживают столь слабые различия в плотности.
Вы также можете устанавливать значения свойства с помощью чисел от 100 до 900, но это тоже не очень хорошо поддерживается шрифтами и браузерами и редко применяется.
Значение по умолчанию: | normal |
---|---|
Применяется: | ко всем элементам |
Анимируется: | да |
Наследуется: | да |
Версия: | CSS1 |
Синтаксис JavaScript: | object.style.fontWeight="900" |
Синтаксис
font-weight: normal|bold|bolder|lighter|число|inherit;
Значения свойства
Значение | Описание |
---|---|
normal | Определяет стандартное написание символов. |
bold | Задает жирное начертание символов в тексте. |
bolder | Тоже самое, что и bold. |
lighter | тоже самое, что и normal. |
100 200 300 400 500 600 700 800 900 |
Определяет толщину шрифта по заданному значению, от 0 до 500 - стандартное начертание шрифта, от 600 до 900 - жирное начертание. |
inherit | Указывает, что значение наследуется от родительского элемента. |
Пример
Следите за изменением шрифта.
div {
font-weight: normal;
}
Свойство font-weight | CSS
Свойство CSS font-weight задает толщину шрифта, оно зависит либо от установленных правил начертания в семействе шрифтов, либо от толщины, определенной в браузере.
span { font-weight: bold; }
В качестве значения свойство font-weight принимает ключевое слово или числовое значение. Доступные ключевые слова:
- normal;
- bold;
- bolder;
- lighter.
Доступные числовые значения:
- 100;
- 200;
- 300;
- 400;
- 500;
- 600;
- 700;
- 800;
- 900.
Значение ключевого слова normal соответствует числовому значению 400, а значение CSS font weight bold — числовому значению 700.
Чтобы к шрифту мог быть применен другой размер, кроме 400 или 700, для него должны быть установлены встроенные правила начертания с соответствующими им числовыми коэффициентами.
Если шрифт имеет жирную («700«) или обычную («400«) версию, то браузер будет использовать их. Если они не доступны, браузер будет имитировать собственную жирную или нормальную версию. Для шрифтов часто используют такие названия, как «Regular» и «Light«, чтобы определить альтернативные значения толщины шрифта.
Следующая демо-версия иллюстрирует использование альтернативных значений толщины:
Посмотреть демо — версию
В приведенной выше демо-версии используется бесплатный шрифт Open Sans, реализуемый с помощью API Google Web Fonts. Шрифт загружается со всеми доступными значениями толщины. С помощью свойства CSS font-weight в тексте каждого абзаца отображаются различные доступные версии. Недоступная версия выводится как логически ближайшая толщина.
Обычные шрифты, такие как Arial, Helvetica, Georgia и т.д. не имеют другой толщины, кроме 400 и 700. Если бы в демо-версии использовался один из этих шрифтов, то во всех абзацах мы увидели бы только две его версии.
Значения ключевых слов «bolder» и «lighter» зависят от вычисляемой толщины шрифта родительского элемента. Браузер будет искать ближайшую к «bolder» или «lighter» толщину в семействе шрифта. Иначе браузер просто установит «400» или «700«.
Дочерние элементы не наследуют значения ключевых слов «bolder» и «lighter«, но вместо этого наследуют вычисленную толщину.
Chrome | Safari | Firefox | Opera | IE | Android | iOS |
Работает | Работает | Работает | Работает | Работает | Работает |
Данная публикация представляет собой перевод статьи «font-weight» , подготовленной дружной командой проекта Интернет-технологии.ру
font-weight - Веб-технології для розробників
This translation is incomplete. Please help translate this article from English
The font-weight
CSS property specifies the weight (or boldness) of the font. The font weights available to you will depend on the font-family
you are using. Some fonts are only available in normal
and bold
.
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
Syntax
/* Keyword values */ font-weight: normal; font-weight: bold; /* Keyword values relative to the parent */ font-weight: lighter; font-weight: bolder; /* Numeric keyword values */ font-weight: 100; font-weight: 200; font-weight: 300; font-weight: 400; font-weight: 500; font-weight: 600; font-weight: 700; font-weight: 800; font-weight: 900; /* Global values */ font-weight: inherit; font-weight: initial; font-weight: unset;
The font-weight
property is specified using a single keyword value from the list below.
Values
normal
- Normal font weight. Same as
400
. bold
- Bold font weight. Same as
700
. lighter
- One font weight lighter than the parent element (among the available weights of the font).
bolder
- One font weight heavier than the parent element (among the available weights of the font).
100
,200
,300
,400
,500
,600
,700
,800
,900
- Numeric font weights for fonts that provide more than just
normal
andbold
.
Fallback weights
If the exact weight given is unavailable, then the following heuristic is used to determine the weight actually rendered:
- If a weight greater than
is given, the closest available heavier weight is used (or, if there is none, the closest available lighter weight). - If a weight less than
400
is given, the closest available lighter weight is used (or, if there is none, the closest available heavier weight). - If a weight of exactly
400
is given, then500
is used. If500
is not available, then the heuristic for font weights less than 400 is used. - If a weight of exactly
500
is given, then400
is used. If400
is not available, then the heuristic for font weights less than 400 is used.
This means that for fonts that provide only normal
and bold
, 100
-500
are normal
, and 600
-900
are bold
.
Meaning of relative weights
When lighter
or bolder
is specified, the following chart shows how the absolute font weight of the element is determined:
Inherited value | bolder |
lighter |
---|---|---|
100 | 400 | 100 |
200 | 400 | 100 |
300 | 400 | 100 |
400 | 700 | 100 |
500 | 700 | 100 |
600 | 900 | 400 |
700 | 900 | 400 |
800 | 900 | 700 |
900 | 900 | 700 |
Common weight name mapping
The numerical values (100
to 900
) roughly correspond to the following common weight names:
Value | Common weight name |
---|---|
100 | Thin (Hairline) |
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) |
Interpolation
A font-weight
value is interpolated via discrete steps (multiples of 100). The interpolation happens in real number space and is converted to an integer by rounding to the nearest multiple of 100, with values halfway between multiples of 100 rounded towards positive infinity.
Formal syntax
<font-weight-absolute> | bolder | lighterwhere
<font-weight-absolute> = normal | bold | <number>
Examples
HTML
<p> Alice was beginning to get very tired of sitting by her sister on the bank, and of having nothing to do: once or twice she had peeped into the book her sister was reading, but it had no pictures or conversations in it, 'and what is the use of a book,' thought Alice 'without pictures or conversations?' </p> <div>I'm heavy<br/> <span>I'm lighter</span> </div>
CSS
/* Set paragraph text to be bold. */ p { font-weight: bold; } /* Set div text to two steps heavier than normal but less than a standard bold. */ div { font-weight: 600; } /* Set span text to be one step lighter than its parent. */ span { font-weight: lighter; }
Result
Specifications
Browser compatibility
Update compatibility data on GitHubDesktop | Mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | Android webview | Chrome for Android | Firefox for Android | Opera for Android | Safari on iOS | Samsung Internet | |
font-weight | Chrome Full support 2 | Edge Full support 12 | Firefox Full support 1 | IE Full support 3 | Opera Full support 3.5 | Safari Full support 1 | WebView Android Full support 1 | Chrome Android Full support 18 | Firefox Android Full support 4 | Opera Android Full support 10.1 | Safari iOS Full support 1 | Samsung Internet Android Full support 1.0 |
<number> syntax | Chrome Full support 62 | Edge Full support 17 | Firefox Full support 61 | IE No support No | Opera Full support 49 | Safari Full support 11 | WebView Android Full support 62 | Chrome Android Full support 62 | Firefox Android Full support 61 | Opera Android ? | Safari iOS Full support 11 | Samsung Internet Android Full support 8.0 |
Legend
- Full support
- Full support
- No support
- No support
- Compatibility unknown
- Compatibility unknown