15.8 Shorthand font property: the ‘font’ property
Name: | font |
---|---|
Value: | ? [ / ]? ] | caption | icon | menu | message-box | small-caption | status-bar | |
Initial: | see individual properties |
Applies to: | all elements |
Inherited: | yes |
Percentages: | see individual properties |
Media: | |
Computed value: | see individual properties |
The property is,
except as described , a shorthand property for
setting
,
,
,
,
and
at the same
place in the style
sheet. The syntax of this property is based on a traditional
typographical shorthand notation to set multiple properties related to
fonts.
All font-related properties are first reset to their initial values,
including those listed in the preceding paragraph.
Then, those properties that are given explicit values in the
shorthand are set to those values.
For a definition of allowed and initial values, see the previously defined properties.
p { font: 12px/14px sans-serif } p { font: 80% sans-serif } p { font: x-large/110% "New Century Schoolbook", serif } p { font: bold italic large Palatino, serif } p { font: normal small-caps 120%/120% fantasy }
In the second rule, the font size percentage value (‘80%’) refers
to the font size of the parent element. In the third rule, the line
height percentage refers to the font size of the element itself.
In the first three rules above, the ‘font-style’, ‘font-variant’
and ‘font-weight’ are not explicitly mentioned, which means they are
all three set to their initial value (‘normal’). The fourth rule sets
the ‘font-weight’ to ‘bold’, the ‘font-style’ to ‘italic’ and
implicitly sets ‘font-variant’ to ‘normal’.
The fifth rule sets the ‘font-variant’ (‘small-caps’), the
‘font-size’ (120% of the parent’s font), the ‘line-height’ (120% times
the font size) and the ‘font-family’ (‘fantasy’). It follows that the
keyword ‘normal’ applies to the two remaining properties: ‘font-style’
and ‘font-weight’.
The following values refer to system fonts:
- caption
- The font used for captioned controls (e.g., buttons, drop-downs, etc.).
- icon
- The font used to label icons.
- menu
- The font used in menus (e.g., dropdown menus and menu lists).
- message-box
- The font used in dialog boxes.
- small-caption
- The font used for labeling small controls.
- status-bar
- The font used in window status bars.
System fonts may only be set as a whole; that is, the font
family, size, weight, style, etc. are all set at the same time.
These values may then be altered individually if desired. If no
font with the indicated characteristics exists on a given platform,
the user agent should either intelligently substitute (e.g., a smaller
version of the ‘caption’ font might be used for the ‘small-caption’
font), or substitute a user agent default font. As for regular fonts,
if, for a system font, any of the individual properties are not part
of the operating system’s available user preferences, those properties
should be set to their initial values.
That is why this property is «almost» a shorthand property: system
fonts can only be specified with this property, not with itself, so allows authors to do more than the
sum of its subproperties. However, the individual properties such as are still given values taken from the system font, which can be independently varied.
button { font: 300 italic 1.3em/1.7em "FB Armada", sans-serif } button p { font: menu } button p em { font-weight: bolder }
If the font used for dropdown menus on a particular system
happened to be, for example, 9-point Charcoal, with a weight of 600, then P
elements that were descendants of BUTTON would be displayed as if
this rule were in effect:
button p { font: 600 9px Charcoal }
Because the shorthand
property resets any property not explicitly given a value
to its initial value, this has the same effect as this declaration:
button p { font-family: Charcoal; font-style: normal; font-variant: normal; font-weight: 600; font-size: 9px; line-height: normal; }
previous
next
properties
index
# Font Variant
Attributes:
**normal**
Default attribute of fonts.
**small-caps**
Sets every letter to uppercase, but makes the lowercase letters(from original text) smaller in size than the letters that originally uppercase.
CSS:
HTML:
OUPUT:
Note:
The font-variant property is a shorthand for the properties: font-variant-caps, font-variant-numeric, font-variant-alternates, font-variant-ligatures, and font-variant-east-asian.
Syntax
- font: font-size font-family;
- font-style: font-style
- font-variant: font-variant
- font-weight: font-weight;
- font-size: font-size;
- line-height: line-height;
- font-family: font-family;
- color: color;
- quotes: none|string|initial|inherit;
- font-stretch: font-stretch;
- text-align: text-align;
- text-indent: length|initial|inherit;
- text-overflow: clip|ellipsis|string|initial|inherit;
- text-transform: none|capitalize|uppercase|lowercase|initial|inherit;
- text-shadow: h-shadow v-shadow blur-radius color|none|initial|inherit;
- font-size-adjust: number|none|initial|inherit;
- font-stretch: ultra-condensed|extra-condensed|condensed|semi-condensed|normal|semi-expanded|expanded|extra-expanded|ultra-expanded|initial|inherit;
- hyphens: none | manual | auto;
- tab-size: number|length|initial|inherit;
- letter-spacing: normal|length|initial|inherit;
- word-spacing: normal|length|initial|inherit;
Parameters
Parameter | Details |
---|---|
font-style | or |
font-variant | or |
font-weight | , or numeric from 100 to 900. |
font-size | The font size given in , , , or any other valid CSS measurement |
line-height | The line height given in , , , or any other valid CSS measurement |
font-family | This is for defining the family’s name. |
color | Any valid , like , , etc. |
font-stretch | Whether or not to use a confenced or expanded face from font. Valid values are , , , , , , , or |
text-align | , , , , , , |
text-decoration | , , , , , ; |
# The Font Shorthand
With the syntax:
You can have all your font-related styles in one declaration with the shorthand. Simply use the property, and put your values in the correct order.
For example, to make all elements bold with a font size of 20px and using Arial as the font family typically you would code it as follows:
However with the font shorthand it can be condensed as follows:
Note: that since , , and are optional, the three of them are skipped in this example. It is important to note that using the shortcut resets the other attributes not given. Another important point is that the two necessary attributes for the font shortcut to work are and . If they are not both included the shortcut is ignored.
Initial value for each of the properties:
- – depends on user agent
font-feature-settings
Эта настройка позволяет включить или выключить некоторые возможности шрифта, например, лигатуры или отображение цифр в старом стиле:
Фичи из демо:
- — лигатуры (когда для удобочитаемости два символа отображаются как один)
- — отображение строчных как маленьких заглавных
- — отображение дробей
- — цифры в старом стиле
- — перечеркнутый ноль
Если фичу нужно включить, достаточно её имени, например:
Хотя запись типа помогает лучше понять что происходит в коде.
Если же нужно выключить, обязательно добавлять :
Некоторые фичи включены по умолчанию, например, разные виды лигатур: , и . Подробнее можно почитать в .
Здесь приведено лишь небольшое количество возможностей, полный список с подробными описаниями есть в спецификации OpenType.
Много примеров с кодом можно найти здесь: OpenType features in CSS.
Как уже говорилось выше, — это низкоуровневая настройка. Спецификация рекомендует, по возможности, использовать высокоуровневые варианты, например:
- для управления лигатурами ()
- для приведения строчных к заглавным ()
- для управления отображением цифр ()
Больше вариантов можно найти в разделе спецификации .
может использоваться для получения более или менее радикального варианта шрифта:
Ещё интереснее распорядился фичами автор шрифта dT Jakob Variable Concept: он сделал не только вариативный шрифт, но и слоёный, и стиль для каждого из слоёв включается с помощью лигатур:
Не уверена, что это правильное использование лигатур, но вариант, безусловно, интересный.
Using CSS feature detection for implementation
Since not all properties are evenly implemented, it’s good practice to set up your CSS using feature detection to utilize the correct properties, with as the fallback.
For example, small caps can be set several ways, but if you want to ensure that no matter what the underlying capitalization is that you end up with everything in small caps, it requires 2 settings with versus a single property value using .
.small-caps { font-feature-settings: "smcp", "c2sc"; } @supports (font-variant-caps: all-small-caps) { .small-caps { font-feature-settings: normal; font-variant-caps: all-small-caps; } }
Свойства font-weight, font-style, text-decoration и другие
С помощью свойства стилей font-weight задают «жирность» шрифта. Синтаксис:
font-weight: normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900
В качестве значения свойства может использоваться одно из семи числовых значений от 100 до 900, либо одно из именованных normal, bold, bolder, lighter. Значение normal соответствует 400, а bold — 7000. Но на практике большинство браузеров не поддерживают атрибут font-weight в полной мере. Поэтому все значения, которые меньше 400 будут соответствовать normal, а все, что больше bold. Причем значения bolder и lighter не работают.
Пример использования:
em { font-weight: bold; }
Свойство CSS font-style задает начертание шрифта. Для него доступны три значения: normal, italic и oblique. Но на практике используют только первые два, где «normal» устанавливает нормальное начертание шрифта, а значение «italic» заставляет браузер выводить текст курсивным начертанием.
С помощью свойства text-decoration можно задавать различные украшательства тексту, такие как подчеркивание текста или зачеркивание:
text-decoration: none|underline|overline|line-through|blink
Для этого атрибута доступны пять значений:
- none — отменяет все эффекты, в том числе отменяет подчеркивание у ссылок, которое задано по умолчанию;
- underline — устанавливает подчеркнутые текст;
- overline — «надчеркивает» текст, то есть проводит линию над текстом;
- line-through — зачеркивает текст;
- blink — устанавливает мигающий текст. Такой текст периодически, примерно раз в секунду исчезает, потом вновь появляется на прежнем месте. Это значение в настоящее время не поддерживается браузерами и осуждается в CSS3.
По умолчанию, для большинства элементов текст выводится без эффектов. Но некоторые html элементы отображают текст с подчеркиванием, в частности гиперссылки (тег a).
Поэтому, кроме ссылок, на веб-странице подчеркиванием лучше ничего не выделять. Потому что пользователи подсознательно решат, что раз подчеркнуто — значит по этому можно кликнуть для перехода. И выделяя подчеркиванием обычный текст, вы вводите пользователя в заблуждение.
Нюансом свойства text-decoration является то, что для него можно указать сразу несколько значений:
text-decoration:underline overline line-through;
Результат будет такой:
перечеркнутый подчеркнутый и надчеркнутый текст!
Свойство стиля text-transform позволяет задавать регистр символов текста:
text-transform: capitalize|uppercase|lowercase|none
Свойство может иметь одно из четырех значений:
- capitalize — преобразовывает к верхнему регистру первую букву каждого слова;
- uppercase — текст в верхнем регистре;
- lowercase — текст в нижнем регистре;
- none — не меняет регистр символов.
Для увеличения и уменьшения расстояния между строками текста используется атрибут line-height. В качестве значения можно задавать как абсолютную так и относительную величину расстояния, указав соответствующую единицу измерения (px, pt, em и др.). В случае отсутствия единицы измерения указанное значение воспринимается браузером как множитель. Например, значение 1.5 устанавливает полуторный междустрочный интервал:
p { line-height: 1.5 }
Для управления расстоянием между символами текста существует свойство letter-spacing. Оно позволяет задавать дополнительное расстояние между буквами, которое будет прибавляться к изначальному. В качестве значений принимаются любые единицы длины, принятые в CSS — пиксели (px), пункты (pt) и др. Допустимо использовать отрицательные значения. В этом случае расстояние между символами уменьшится:
em { letter-spacing: 5px; }
Аналогичный атрибут word-spacing задает дополнительное расстояние между словами текста:
h1 { word-spacing: 5px }
Ну и напоследок необходимо рассмотреть свойство стиля font, позволяющее задавать сразу несколько параметров для шрифта. Синтаксис:
font: font-size font-family
Обязательными параметрами являются только размер шрифта и его имя, остальные параметры могут отсутствовать.
Например, чтобы задать для текста абзацев шрифт «Times New Roman» размером 10 пунктов, достаточно написать следующее правило CSS:
p { font: 10pt «Times New Roman» }
А если мы захотим выводить текст заголовков первого уровня рубленым шрифтом размером 15 пикселей и курсивным начертанием, то подойдет такое правило:
p { font: italic 12px sans-serif }
Best Practices
- Use variable fonts and the font-variation-settings property judiciously, as they can have a significant impact on page loading times and performance.
- Consider using a fallback font stack for browsers that do not support variable fonts, or use feature detection to provide a fallback font only when necessary.
- Be mindful of legibility when adjusting font variations. Some variations may make text more difficult to read, especially at small font sizes.
- Test your font-variation-settings styles on different devices and screen sizes to ensure that they are legible and effective.
- Use custom variation values sparingly, and only when they are necessary to achieve a specific design goal.
15.2 Font matching algorithm
Because there is no accepted, universal taxonomy of font
properties, matching of properties to font faces must be done
carefully. The properties are matched in a well-defined order to
insure that the results of this matching process are as consistent as
possible across UAs (assuming that the same library of font faces is
presented to each of them).
- The User Agent makes (or accesses) a database of relevant CSS 2.2
properties of all the fonts of which the UA is aware.
If there are two fonts with exactly the same properties, the user
agent selects one of them. - At a given element and for each character in that element, the UA
assembles the font properties applicable to that element. Using the
complete set of properties, the UA uses the ‘font-family’ property to
choose a tentative font family. The remaining properties are tested
against the family according to the matching criteria described with
each property. If there are matches for all the remaining properties,
then that is the matching font face for the given element or character. - If there is no matching font face within the ‘font-family’ being
processed by step 2, and if there is a next alternative ‘font-family’
in the font set, then repeat step 2 with the next alternative
‘font-family’. - If there is a matching font face, but it does not contain a glyph
for the current character, and if there is a next alternative
‘font-family’ in the font sets, then repeat step 2 with the next
alternative ‘font-family’. - If there is no font within the family selected in 2, then use a
UA-dependent default ‘font-family’ and repeat step 2, using the best
match that can be obtained within the default font. If a particular
character cannot be displayed using this font, then the UA may use other
means to determine a suitable font for that character. The UA should map
each character for which it has no suitable font to a visible symbol
chosen by the UA, preferably a «missing character» glyph from one of the
font faces available to the UA.
(The above algorithm can be optimized to avoid having to revisit
the CSS 2.2 properties for each character.)
The per-property matching rules from (2) above are as follows:
-
is tried first. ‘Italic’
will be satisfied if there is either a face in the UA’s font database
labeled with the CSS keyword ‘italic’ (preferred) or ‘oblique’.
Otherwise the values must be matched exactly or font-style will fail. -
is tried next. ‘Small-caps’ matches (1) a
font labeled as ‘small-caps’, (2) a font in which the small caps are
synthesized, or (3) a font where all lowercase letters are replaced by
upper case letters. A small-caps font may be synthesized by
electronically scaling uppercase letters from a normal font.
‘normal’ matches a font’s normal (non-small-caps) variant. A font cannot fail to have a normal variant. A font
that is only available as small-caps shall be selectable as either a ‘normal’ face or a ‘small-caps’ face. -
is matched next, it will
never fail. (See ‘font-weight’ below.) -
must be matched within a
UA-dependent margin of tolerance. (Typically, sizes for scalable fonts
are rounded to the nearest whole pixel, while the tolerance for
bitmapped fonts could be as large as 20%.) Further computations, e.g.,
by ’em’ values in other properties, are based on
the computed value of ‘font-size’.
Font feature settings
is the ‘low level syntax’ that allows explicit access to every named available OpenType feature. This gives a lot of control, but has some disadvantages in how it impacts inheritance and — as mentioned above — if you wish to change one setting, you have to redeclare the entire string (unless you’re using CSS custom properties to set the values). Because of this, it’s best to use the standard properties shown above wherever possible.
There a huge number of possible features. You can see examples of a number of them above, and there are several resources available for finding more of them.
The general syntax looks like this:
.small-caps { font-feature-settings: "smcp", "c2sc"; }
According to the specification you can either supply just the 4-character feature code or supply a 1 following the code (for enabling that feature) or a 0 (zero) to disable it. This is helpful if you have a feature like ligatures enabled by default but you would like to turn them off, like so:
.no-ligatures { font-feature-settings: "liga" 0, "dlig" 0; }
More on font-feature-settings codes
- ‘The Complete CSS Demo for OpenType Features’ (can’t vouch for the truth of the name, but it’s pretty big)
- A list of OpenType features on Wikipedia
CSS Справочники
CSS СправочникCSS ПоддержкаCSS СелекторыCSS ФункцииCSS ЗвукCSS Веб шрифтыCSS АнимацииCSS ДлиныCSS Конвертер px-emCSS Названия цветаCSS Значения цветаCSS по умолчаниюCSS Символы
CSS Свойства
align-content
align-items
align-self
all
animation
animation-delay
animation-direction
animation-duration
animation-fill-mode
animation-iteration-count
animation-name
animation-play-state
animation-timing-function
backface-visibility
background
background-attachment
background-blend-mode
background-clip
background-color
background-image
background-origin
background-position
background-repeat
background-size
border
border-bottom
border-bottom-color
border-bottom-left-radius
border-bottom-right-radius
border-bottom-style
border-bottom-width
border-collapse
border-color
border-image
border-image-outset
border-image-repeat
border-image-slice
border-image-source
border-image-width
border-left
border-left-color
border-left-style
border-left-width
border-radius
border-right
border-right-color
border-right-style
border-right-width
border-spacing
border-style
border-top
border-top-color
border-top-left-radius
border-top-right-radius
border-top-style
border-top-width
border-width
bottom
box-decoration-break
box-shadow
box-sizing
caption-side
caret-color
@charset
clear
clip
color
column-count
column-fill
column-gap
column-rule
column-rule-color
column-rule-style
column-rule-width
column-span
column-width
columns
content
counter-increment
counter-reset
cursor
direction
display
empty-cells
filter
flex
flex-basis
flex-direction
flex-flow
flex-grow
flex-shrink
flex-wrap
float
font
@font-face
font-family
font-kerning
font-size
font-size-adjust
font-stretch
font-style
font-variant
font-weight
grid
grid-area
grid-auto-columns
grid-auto-flow
grid-auto-rows
grid-column
grid-column-end
grid-column-gap
grid-column-start
grid-gap
grid-row
grid-row-end
grid-row-gap
grid-row-start
grid-template
grid-template-areas
grid-template-columns
grid-template-rows
hanging-punctuation
height
hyphens
@import
isolation
justify-content
@keyframes
left
letter-spacing
line-height
list-style
list-style-image
list-style-position
list-style-type
margin
margin-bottom
margin-left
margin-right
margin-top
max-height
max-width
@media
min-height
min-width
mix-blend-mode
object-fit
object-position
opacity
order
outline
outline-color
outline-offset
outline-style
outline-width
overflow
overflow-x
overflow-y
padding
padding-bottom
padding-left
padding-right
padding-top
page-break-after
page-break-before
page-break-inside
perspective
perspective-origin
pointer-events
position
quotes
resize
right
tab-size
table-layout
text-align
text-align-last
text-decoration
text-decoration-color
text-decoration-line
text-decoration-style
text-indent
text-justify
text-overflow
text-shadow
text-transform
top
transform
transform-origin
transform-style
transition
transition-delay
transition-duration
transition-property
transition-timing-function
unicode-bidi
user-select
vertical-align
visibility
white-space
width
word-break
word-spacing
word-wrap
writing-mode
z-index
Glossary
Let’s notify the terms used in this article.
And the first and the main question is, what is font?
Font is the set of graphical representations of symbols. The way a font looks depends on the font’s parameters such as type family, typeface, font proportions, etc.
Glyph — is a graphical representation of a symbol. It is aimed to depict a distinguished character.
The glyph is a unique shape, design, or way it looks. It is how the character is rendered in a particular font.
In the image below, you see the glyph rendered in different fonts.
Typeface — is a specific design of a font. It has size, weight, width, slope, and other variations. It is often confused with the term font. The point is that fonts have particular (fixed) parameters. So the difference is in having variations. Therefore every variation in a typeface is an individual font.
The term typeface is also often mixed up with the type/font family.
So, what is font family?
Font family is a group of related, similar in design typefaces. The members of a family have a common name.
The image below will clarify to you the difference between font, typeface and font family.
15.4 Font styling: the ‘font-style’ property
Name: | font-style |
---|---|
Value: | normal | italic | oblique | |
Initial: | normal |
Applies to: | all elements |
Inherited: | yes |
Percentages: | N/A |
Media: | |
Computed value: | as specified |
The ‘font-style’ property selects between normal (sometimes
referred to as «roman» or «upright»), italic and oblique faces within
a font family.
A value of ‘normal’ selects a font that is classified as ‘normal’
in the UA’s font database, while ‘oblique’ selects a font that is
labeled ‘oblique’. A value of ‘italic’ selects a font that is labeled
‘italic’, or, if that is not available, one labeled ‘oblique’.
The font that is labeled ‘oblique’ in the UA’s font database may
actually have been generated by electronically slanting a normal font.
Fonts with Oblique, Slanted or Incline in their names will
typically be labeled ‘oblique’ in the UA’s font database. Fonts with
Italic, Cursive or Kursiv in their names will
typically be labeled ‘italic’.
h1, h2, h3 { font-style: italic } h1 em { font-style: normal }
In the example above, emphasized text within ‘H1’ will appear in a
normal face.