font-family

CSS Fonts

Choosing the right font for your website is important!

Font Selection is Important

Choosing the right font has a huge impact on how the readers experience a website.

The right font can create a strong identity for your brand.

Using a font that is easy to read is important. The font adds value to your text. It is also important to choose the correct color and text size for the font.

Generic Font Families

In CSS there are five generic font families:

  1. Serif fonts have a small stroke at the edges of each letter. They create a sense of formality and elegance.
  2. Sans-serif fonts have clean lines (no small strokes attached). They create a modern and minimalistic look.
  3. Monospace fonts — here all the letters have the same fixed width. They create a mechanical look.
  4. Cursive fonts imitate human handwriting.
  5. Fantasy fonts are decorative/playful fonts.

All the different font names belong to one of the generic font families.

Difference Between Serif and Sans-serif Fonts

Note: On computer screens, sans-serif fonts are considered easier to read than serif fonts.

Some Font Examples

Generic Font Family Examples of Font Names
Serif Times New Roman
Georgia
Garamond
Sans-serif Arial
Verdana
Helvetica
Monospace Courier New
Lucida Console
Monaco
Cursive Brush Script MT
Lucida Handwriting
Fantasy Copperplate
Papyrus
Читайте также:  Селекторы атрибутов

The CSS font-family Property

In CSS, we use the font-family property to specify the font of a text.

Note: If the font name is more than one word, it must be in quotation marks, like: «Times New Roman».

Tip: The font-family property should hold several font names as a «fallback» system, to ensure maximum compatibility between browsers/operating systems. Start with the font you want, and end with a generic family (to let the browser pick a similar font in the generic family, if no other fonts are available). The font names should be separated with comma. Read more about fallback fonts in the next chapter.

Example

Specify some different fonts for three paragraphs:

.p1 <
font-family: «Times New Roman», Times, serif;
>

.p2 font-family: Arial, Helvetica, sans-serif;
>

.p3 font-family: «Lucida Console», «Courier New», monospace;
>

Источник

font-family

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

Когда браузер встречает первый шрифт в списке, он проверяет его наличие на компьютере пользователя. Если такого шрифта нет, берется следующее имя из списка и также анализируется на присутствие. Поэтому несколько шрифтов увеличивает вероятность, что хотя бы один из них будет обнаружен на клиентском компьютере. Заканчивают список обычно ключевым словом, которое описывает тип шрифта — serif , sans-serif , cursive , fantasy или monospace . Таким образом, последовательность шрифтов лучше начинать с экзотических типов и заканчивать обобщенным именем, которое задает вид начертания.

Синтаксис

font-family: имя шрифта [, имя шрифта[, . ]] | inherit

Значения

Любое количество имен шрифтов разделенных запятыми. Универсальные семейства шрифтов:

  • serif — шрифты с засечками (антиквенные), типа Times;
  • sans-serif — рубленные шрифты (шрифты без засечек или гротески), типичный представитель — Arial;
  • cursive — курсивные шрифты;
  • fantasy — декоративные шрифты;
  • monospace — моноширинные шрифты, ширина каждого символа в таком семействе одинакова (шрифт Courier).

HTML5 CSS2.1 IE Cr Op Sa Fx

     h1 < font-family: Geneva, Arial, Helvetica, sans-serif; >p 

Duis te feugifacilisi

Lorem ipsum dolor sit amet, 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.

Применение свойства font-family

Рис. 1. Применение свойства font-family

Объектная модель

[window.]document.getElementById(» elementID «).style.fontFamily

Браузеры

Internet Explorer до версии 7.0 включительно не поддерживает значение inherit .

Источник

CSS font-family Property

The font-family property specifies the font for an element.

The font-family property can hold several font names as a «fallback» system. If the browser does not support the first font, it tries the next font.

There are two types of font family names:

  • family-name — The name of a font-family, like «times», «courier», «arial», etc.
  • generic-family — The name of a generic-family, like «serif», «sans-serif», «cursive», «fantasy», «monospace».

Start with the font you want, and always end with a generic family, to let the browser pick a similar font in the generic family, if no other fonts are available.

Note: Separate each value with a comma.

Note: If a font name contains white-space, it must be quoted. Single quotes must be used when using the «style» attribute in HTML.

Default value: depends on the browser
Inherited: yes
Animatable: no. Read about animatable
Version: CSS1
JavaScript syntax: object.style.fontFamily=»Verdana,sans-serif» 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
family-name / generic-family A prioritized list of font family names and/or generic family names Demo ❯
initial Sets this property to its default value. Read about initial
inherit Inherits this property from its parent element. Read about inherit

Источник

font-family

The font-family CSS property specifies a prioritized list of one or more font family names and/or generic family names for the selected element.

Try it

Values are separated by commas to indicate that they are alternatives. The browser will select the first font in the list that is installed or that can be downloaded using a @font-face at-rule.

It is often convenient to use the shorthand property font to set font-size and other font related properties all at once.

You should always include at least one generic family name in a font-family list, since there’s no guarantee that any given font is available. This lets the browser select an acceptable fallback font when necessary.

The font-family property specifies a list of fonts, from highest priority to lowest. Font selection does not stop at the first font in the list that is on the user’s system. Rather, font selection is done one character at a time, so that if an available font does not have a glyph for a needed character, the latter fonts are tried. When a font is only available in some styles, variants, or sizes, those properties may also influence which font family is chosen.

Syntax

/* A font family name and a generic family name */ font-family: "Gill Sans Extrabold", sans-serif; font-family: "Goudy Bookletter 1911", sans-serif; /* A generic family name only */ font-family: serif; font-family: sans-serif; font-family: monospace; font-family: cursive; font-family: fantasy; font-family: system-ui; font-family: ui-serif; font-family: ui-sans-serif; font-family: ui-monospace; font-family: ui-rounded; font-family: emoji; font-family: math; font-family: fangsong; /* Global values */ font-family: inherit; font-family: initial; font-family: revert; font-family: revert-layer; font-family: unset; 

The font-family property lists one or more font families, separated by commas. Each font family is specified as either a or a value.

The example below lists two font families, the first with a and the second with a :

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

Values

The name of a font family. For example, «Times» and «Helvetica» are font families. Font family names containing whitespace should be quoted. For example: «Comic Sans MS».

Generic font families are a fallback mechanism, a means of preserving some of the style sheet author’s intent when none of the specified fonts are available. Generic family names are keywords and must not be quoted. A generic font family should be the last item in the list of font family names. The following keywords are defined:

Glyphs have finishing strokes, flared or tapering ends, or have actual serifed endings.

For example: Lucida Bright, Lucida Fax, Palatino, Palatino Linotype, Palladio, URW Palladio, serif.

Glyphs have stroke endings that are plain.

For example: Open Sans, Fira Sans, Lucida Sans, Lucida Sans Unicode, Trebuchet MS, Liberation Sans, Nimbus Sans L, sans-serif.

All glyphs have the same fixed width.

For example: Fira Mono, DejaVu Sans Mono, Menlo, Consolas, Liberation Mono, Monaco, Lucida Console, monospace.

Glyphs in cursive fonts generally have either joining strokes or other cursive characteristics beyond those of italic typefaces. The glyphs are partially or completely connected, and the result looks more like handwritten pen or brush writing than printed letter work.

For example: Brush Script MT, Brush Script Std, Lucida Calligraphy, Lucida Handwriting, Apple Chancery, cursive.

Fantasy fonts are primarily decorative fonts that contain playful representations of characters.

For example: Papyrus, Herculanum, Party LET, Curlz MT, Harrington, fantasy.

Glyphs are taken from the default user interface font on a given platform. Because typographic traditions vary widely across the world, this generic is provided for typefaces that don’t map cleanly into the other generics.

The default user interface serif font.

The default user interface sans-serif font.

The default user interface monospace font.

The default user interface font that has rounded features.

This is for the particular stylistic concerns of representing mathematics: superscript and subscript, brackets that cross several lines, nesting expressions, and double struck glyphs with distinct meanings.

Fonts that are specifically designed to render emoji.

A particular style of Chinese characters that are between serif-style Song and cursive-style Kai forms. This style is often used for government documents.

Valid family names

Font family names must either be given quoted as strings, or unquoted as a sequence of one or more identifiers. This means that punctuation characters and digits at the start of each token must be escaped in unquoted font family names.

It is a good practice to quote font family names that contain white space, digits, or punctuation characters other than hyphens.

For example, the following declarations are valid:

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

The following declarations are invalid:

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; 

The following example is technically valid but is not recommended:

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

Formal definition

Initial value depends on user agent
Applies to all elements. It also applies to ::first-letter and ::first-line .
Inherited yes
Computed value as specified
Animation type discrete

Formal syntax

Examples

Some common font families

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

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.

Источник

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