- How to Apply Global Font to the Entire HTML Document
- Create HTML
- Add CSS
- Example of applying a global font to the entire HTML document:
- Example of applying a global font to the entire HTML document using the !important rule:
- font
- Синтаксис
- Значения
- Примеры использования
- Объектная модель
- Браузеры
- CSS Fonts
- Font Selection is Important
- Generic Font Families
- Difference Between Serif and Sans-serif Fonts
- Some Font Examples
- The CSS font-family Property
- Example
- HTML Tag
- Syntax
- Example of using HTML tag:
- Result
- CSS Styles
- Example of changing the style of the text with CSS:
- Attributes
- How to style tag?
- Common properties to alter the visual weight/emphasis/size of text in tag:
- Coloring text in tag:
- Text layout styles for tag:
- Other properties worth looking at for tag:
- font
- Синтаксис
- Значения
- Примеры использования
- Объектная модель
- Браузеры
How to Apply Global Font to the Entire HTML Document
Sometimes you may face the situation when there is a need to apply the same font-family and font-size to the entire HTML document.
In this snippet, we’re going to apply a global font format to the whole HTML page.
Here, you can find two examples, one of them with the CSS !important rule applied.
Create HTML
h1>Heading h1> p>Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book. p>
Add CSS
- Add the CSS * (asterisk) selector to select all the elements of the document.
- Set the font-size, font-family, line-height, and color properties.
html * < font-size: 16px; line-height: 1.625; color: #2020131; font-family: Nunito, sans-serif; >
Example of applying a global font to the entire HTML document:
html> html> head> title>Title of the document title> style> html * < font-size: 16px; line-height: 1.625; color: #2020131; font-family: Nunito, sans-serif; > style> head> body> h1>Heading h1> p> Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book. p> body> html>
If you need to ensure that nothing can override what is set in that style, use the CSS !important rule. It is used to ignore the inner formatting of text, i.e., other styles cannot overwrite the styles with !important.
Next, we’ll demonstrate an example where we use the !important rule for all our CSS properties.
Example of applying a global font to the entire HTML document using the !important rule:
html> html> head> title>Title of the document title> style> html * < font-size: 16px !important; line-height: 1.625 !important; color: #2020131 !important; font-family: Nunito, sans-serif !important; > style> head> body> h1>Heading h1> p> Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book. p> body> html>
font
Универсальное свойство, которое позволяет одновременно задать несколько характеристик шрифта и текста.
Синтаксис
font: [font-style||font-variant||font-weight] font-size [/line-height] font-family | inherit
Значения
В качестве обязательных значений свойства font указывается размер шрифта и его семейство. Остальные значения являются опциональными и задаются при желании. Для подробного ознакомления смотрите информацию о каждом свойстве отдельно.
inherit Наследует значение родителя.
Допускается в качестве значения использовать ключевые слова, определяющие шрифт различных элементов операционной системы пользователя.
caption Шрифт для текста элементов форм вроде кнопок. icon Шрифт для текста под иконками. menu Шрифт применяемый в меню. message-box Шрифт для диалоговых окон. small-caption Шрифт для подписей к небольшим элементам управления. status-bar Шрифт для строки состояния окон.
Примеры использования
Из типографики пошла запись указывать через слэш размер шрифта и межстрочное расстояние (интерлиньяж). Поэтому 12pt в данном случае означает размер основного текста в пунктах, а 10pt — интерлиньяж. В качестве семейства указывается рубленый шрифт ( sans-serif ).
Значение bold устанавливает жирное начертание текста, а italic — курсивное. В данном случае их порядок не важен, поэтому bold и italic можно поменять местами. Размер текста задается в процентах, а в качестве гарнитуры используется шрифт с засечками ( serif ).
Значение small-caps принадлежит свойству font-variant и устанавливает текст в виде капители (заглавные буквы уменьшенного размера). Значение normal применяется сразу к двум свойствам: font-style и font-weight .
HTML5 CSS2.1 IE Cr Op Sa Fx
.layer1 < font: 12pt sans-serif; >h1 Duis te feugifacilisi Duis autem dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit au gue duis dolore te feugat nulla facilisi.
Результат данного примера показан на рис. 1.
Рис. 1. Применение свойства font
Объектная модель
[window.]document.getElementById(» elementID «).style.fontБраузеры
Internet Explorer до версии 7.0 включительно не поддерживает значение inherit .
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:
- Serif fonts have a small stroke at the edges of each letter. They create a sense of formality and elegance.
- Sans-serif fonts have clean lines (no small strokes attached). They create a modern and minimalistic look.
- Monospace fonts — here all the letters have the same fixed width. They create a mechanical look.
- Cursive fonts imitate human handwriting.
- 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;
>
HTML Tag
The tag defines the font characteristics. Size, color and typeface are defined by the size , color and face attributes.
Syntax
The tag comes in pairs. The content is written between the opening () and closing () tags.
Example of using HTML tag:
html> html> head> title>Title of the document title> head> body> p> font size="2" color="#1c87c9">Blue text font> p> p> font size="3" color="red">Red text, font size increased. font> p> p> font face="arial" color="#8ebf42">Green text, typeface changed. font> p> body> html>
Result
CSS Styles
To change the text color, use the CSS color property instead of the color attribute. CSS font-family or font-face properties replace the face attribute, and instead of the size attribute, the CSS font-size property is used.
Example of changing the style of the text with CSS:
html> html> head> title>Title of the document title> head> body> p style="font-size:16px; color:#1c87c9;">Blue text. p> p style="font-size:18px; color:red;">Red text, font size increased. p> p style="font-size:18px; color:#8ebf42; font-family:arial;">Green text, typeface changed. p> body> html>
Attributes
Attribute | Value | Description |
---|---|---|
color | rgb (x, x, x) #xxxxxx colorname | Sets the color of the text. |
face | font_family | Sets the typeface. |
size | number | Sets the size of the text. |
How to style tag?
Common properties to alter the visual weight/emphasis/size of text in tag:
- CSS font-style property sets the style of the font. normal | italic | oblique | initial | inherit.
- CSS font-family property specifies a prioritized list of one or more font family names and/or generic family names for the selected element.
- CSS font-size property sets the size of the font.
- CSS font-weight property defines whether the font should be bold or thick.
- CSS text-transform property controls text case and capitalization.
- CSS text-decoration property specifies the decoration added to text, and is a shorthand property for text-decoration-line, text-decoration-color, text-decoration-style.
Coloring text in tag:
- CSS color property describes the color of the text content and text decorations.
- CSS background-color property sets the background color of an element.
Text layout styles for tag:
- CSS text-indent property specifies the indentation of the first line in a text block.
- CSS text-overflow property specifies how overflowed content that is not displayed should be signalled to the user.
- CSS white-space property specifies how white-space inside an element is handled.
- CSS word-break property specifies where the lines should be broken.
Other properties worth looking at for tag:
- CSS text-shadow property adds shadow to text.
- CSS text-align-last property sets the alignment of the last line of the text.
- CSS line-height property specifies the height of a line.
- CSS letter-spacing property defines the spaces between letters/characters in a text.
- CSS word-spacing property sets the spacing between words.
font
Универсальное свойство, которое позволяет одновременно задать несколько характеристик шрифта и текста.
Синтаксис
font: [font-style||font-variant||font-weight] font-size [/line-height] font-family | inherit
Значения
В качестве обязательных значений свойства font указывается размер шрифта и его семейство. Остальные значения являются опциональными и задаются при желании. Для подробного ознакомления смотрите информацию о каждом свойстве отдельно.
inherit Наследует значение родителя.
Допускается в качестве значения использовать ключевые слова, определяющие шрифт различных элементов операционной системы пользователя.
caption Шрифт для текста элементов форм вроде кнопок. icon Шрифт для текста под иконками. menu Шрифт применяемый в меню. message-box Шрифт для диалоговых окон. small-caption Шрифт для подписей к небольшим элементам управления. status-bar Шрифт для строки состояния окон.
Примеры использования
Из типографики пошла запись указывать через слэш размер шрифта и межстрочное расстояние (интерлиньяж). Поэтому 12pt в данном случае означает размер основного текста в пунктах, а 10pt — интерлиньяж. В качестве семейства указывается рубленый шрифт ( sans-serif ).
Значение bold устанавливает жирное начертание текста, а italic — курсивное. В данном случае их порядок не важен, поэтому bold и italic можно поменять местами. Размер текста задается в процентах, а в качестве гарнитуры используется шрифт с засечками ( serif ).
Значение small-caps принадлежит свойству font-variant и устанавливает текст в виде капители (заглавные буквы уменьшенного размера). Значение normal применяется сразу к двум свойствам: font-style и font-weight .
HTML5 CSS2.1 IE Cr Op Sa Fx
.layer1 < font: 12pt sans-serif; >h1 Duis te feugifacilisi Duis autem dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit au gue duis dolore te feugat nulla facilisi.
Результат данного примера показан на рис. 1.
Рис. 1. Применение свойства font
Объектная модель
[window.]document.getElementById(» elementID «).style.fontБраузеры
Internet Explorer до версии 7.0 включительно не поддерживает значение inherit .