- font-weight
- Синтаксис
- Значения
- Объектная модель
- Браузеры
- font-weight
- Syntax
- Values
- Common weight name mapping
- Variable fonts
- Accessibility concerns
- Formal definition
- Formal syntax
- Examples
- Setting normal font weight in a @font-face rule
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- font-weight
- Краткая информация
- Синтаксис
- Значения
- Песочница
- Пример
- Мелодический голос персонажа
- Объектная модель
- Спецификация
- Браузеры
- См. также
- CSS font-weight Property
- Browser Support
- CSS Syntax
- Property Values
- Related Pages
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
font-weight
Устанавливает насыщенность шрифта. Значение устанавливается от 100 до 900 с шагом 100. Сверхсветлое начертание, которое может отобразить браузер, имеет значение 100, а сверхжирное — 900. Нормальное начертание шрифта (которое установлено по умолчанию) эквивалентно 400, стандартный полужирный текст — значению 700.
Синтаксис
Значения
Насыщенность шрифта задаётся с помощью ключевых слов: bold — полужирное начертание, normal — нормальное начертание. Также допустимо использовать условные единицы от 100 до 900. Значения bolder и lighter изменяют жирность относительно насыщенности родителя, соответственно, в большую и меньшую сторону.
HTML5 CSS2.1 IE Cr Op Sa Fx
Duis te feugifacilisi
, 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.
Результат данного примера показан на рис. 1.
Рис. 1. Применение свойства font-weight
Объектная модель
[window.]document.getElementById(» elementID «).style.fontWeightБраузеры
Браузеры обычно не могут адекватно показать требуемую насыщенность шрифта, поэтому переключаются между значениями bold , normal и lighter . На практике же начертание в браузерах обычно ограничено всего двумя вариантами: нормальное начертание и жирное начертание.
font-weight
The font-weight CSS descriptor allows authors to specify font weights for the fonts specified in the @font-face at-rule. The font-weight property can separately be used to set how thick or thin characters in text should be displayed.
For a particular font family, authors can download various font faces which correspond to the different styles of the same font family, and then use the font-weight descriptor to explicitly specify the font face’s weights. The values for the CSS descriptor is same as that of its corresponding font property.
There are generally limited weights available for a particular font family. When a specified weight doesn’t exist, a nearby weight is used. Fonts lacking bold typeface are often synthesized by the user agent. To prevent this, use the font-synthesis shorthand property.
Syntax
/* Single values */ font-weight: normal; font-weight: bold; font-weight: 400; /* Multiple Values */ font-weight: normal bold; font-weight: 300 500;
The font-weight property is described using any one of the values listed below.
Values
Normal font weight. Same as 400 .
Bold font weight. Same as 700 .
In earlier versions of the font-weight specification, the property accepts only keyword values and the numeric values 100, 200, 300, 400, 500, 600, 700, 800, and 900; non-variable fonts can only really make use of these set values, although fine-grained values (e.g. 451) will be translated to one of these values for non-variable fonts.
CSS Fonts Level 4 extends the syntax to accept any number between 1 and 1000, inclusive, and introduces Variable fonts, which can make use of this much finer-grained range of font weights.
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) |
Variable fonts
Most fonts have a particular weight which corresponds to one of the numbers in Common weight name mapping. However some fonts, called variable fonts, can support a range of weights with more or less fine granularity, and this can give the designer a much closer degree of control over the chosen weight.
For TrueType or OpenType variable fonts, the «wght» variation is used to implement varying weights.
Accessibility concerns
People experiencing low vision conditions may have difficulty reading text set with a font-weight value of 100 (Thin/Hairline) or 200 (Extra Light), especially if the font has a low contrast color ratio.
Formal definition
Formal syntax
Examples
Setting normal font weight in a @font-face rule
The following finds a local Open Sans font or imports it, and allows using the font for normal font weights.
@font-face font-family: "Open Sans"; src: local("Open Sans") format("woff2"), url("/fonts/OpenSans-Regular-webfont.woff") format("woff"); font-weight: 400; >
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.
font-weight
Устанавливает насыщенность шрифта. Значение указывается в виде чисел от 100 до 900 с шагом 100 или с помощью заданных ключевых слов.
Краткая информация
Синтаксис
font-weight: bold|bolder|lighter|normal|100|200|300|400|500|600|700|800|900
Синтаксис
Описание | Пример | |
---|---|---|
Указывает тип значения. | ||
A && B | Значения должны выводиться в указанном порядке. | && |
A | B | Указывает, что надо выбрать только одно значение из предложенных (A или B). | normal | small-caps |
A || B | Каждое значение может использоваться самостоятельно или совместно с другими в произвольном порядке. | width || count |
[ ] | Группирует значения. | [ crop || cross ] |
* | Повторять ноль или больше раз. | [,]* |
+ | Повторять один или больше раз. | + |
? | Указанный тип, слово или группа не является обязательным. | inset? |
Повторять не менее A, но не более B раз. | ||
# | Повторять один или больше раз через запятую. | # |
Значения
Насыщенность шрифта задаётся с помощью ключевых слов: bold — жирное начертание и normal — нормальное начертание. Также допустимо использовать условные единицы от 100 до 900. Значения bolder и lighter изменяют жирность относительно насыщенности родителя, соответственно, в большую и меньшую сторону.
Вот как числовые значения влияют на насыщенность шрифта.
- 100 — тонкое начертание;
- 200 — сверхсветлое;
- 300 — светлое;
- 400 — нормальное (аналогично normal );
- 500 — среднее;
- 600 — полужирное;
- 700 — жирное (аналогично bold );
- 800 — сверхжирное;
- 900 — тяжёлое.
Учтите, что не все шрифты поддерживают этот набор. Если указанное значение не поддерживается, то браузер приведёт шрифт к ближайшей насыщенности. К примеру, если вы указали 900 и оно не может быть показано, то браузер в действительности применит значение 700 как ближайшее, которое работает корректно.
Песочница
Винни-Пух был всегда не прочь немного подкрепиться, в особенности часов в одиннадцать утра, потому что в это время завтрак уже давно окончился, а обед ещё и не думал начинаться. И, конечно, он страшно обрадовался, увидев, что Кролик достаёт чашки и тарелки.
@import url(https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900); div < font-family: Roboto, sans-serif; font-weight: >; >
Пример
Мелодический голос персонажа
, соприкоснувшись в чем-то со своим главным антагонистом в постструктурной поэтике, иллюстрирует былинный мифопоэтический хронотоп, об этом свидетельствуют краткость и завершенность формы, бессюжетность, своеобразие тематического развертывания.
!DOCTYPE>
Результат данного примера показан на рис. 1.
Рис. 1. Применение свойства font-weight
Объектная модель
Объект.style.fontWeight
Спецификация
Спецификация | Статус |
---|---|
CSS Fonts Module Level 3 | Возможная рекомендация |
CSS Transitions | Рабочий проект |
CSS Level 2 (Revision 1) | Рекомендация |
CSS Level 1 | Рекомендация |
Спецификация
Каждая спецификация проходит несколько стадий одобрения.
- Recommendation ( Рекомендация ) — спецификация одобрена W3C и рекомендована как стандарт.
- Candidate Recommendation ( Возможная рекомендация ) — группа, отвечающая за стандарт, удовлетворена, как он соответствует своим целям, но требуется помощь сообщества разработчиков по реализации стандарта.
- Proposed Recommendation ( Предлагаемая рекомендация ) — на этом этапе документ представлен на рассмотрение Консультативного совета W3C для окончательного утверждения.
- Working Draft ( Рабочий проект ) — более зрелая версия черновика после обсуждения и внесения поправок для рассмотрения сообществом.
- Editor’s draft ( Редакторский черновик ) — черновая версия стандарта после внесения правок редакторами проекта.
- Draft ( Черновик спецификации ) — первая черновая версия стандарта.
Браузеры
В таблице браузеров применяются следующие обозначения.
- — элемент полностью поддерживается браузером;
- — элемент браузером не воспринимается и игнорируется;
- — при работе возможно появление различных ошибок, либо элемент поддерживается с оговорками.
Число указывает версию браузреа, начиная с которой элемент поддерживается.
См. также
CSS font-weight Property
The font-weight property sets how thick or thin characters in text should be displayed.
Default value: | normal |
---|---|
Inherited: | yes |
Animatable: | yes. Read about animatable Try it |
Version: | CSS1 |
JavaScript syntax: | object.style.fontWeight=»bold» Try it |
Browser Support
The numbers in the table specify the first browser version that fully supports the property.
CSS Syntax
Property Values
Value | Description | Demo |
---|---|---|
normal | Defines normal characters. This is default | Demo ❯ |
bold | Defines thick characters | Demo ❯ |
bolder | Defines thicker characters | Demo ❯ |
lighter | Defines lighter characters | Demo ❯ |
100 200 300 400 500 600 700 800 900 | Defines from thin to thick characters. 400 is the same as normal, and 700 is the same as bold | Demo ❯ |
initial | Sets this property to its default value. Read about initial | |
inherit | Inherits this property from its parent element. Read about inherit |
Related Pages
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.