- Как установить стиль шрифта. CSS-свойство font
- Значения и примеры использования
- Font-family
- Font-style
- Font-variant
- Font-weight
- Font-size
- Line-height
- Наследование
- Нюансы
- Чем заменить свойство font
- Материалы по теме
- How to Change a Webpage Text Font and Color Using CSS
- Expert Q&A
- You Might Also Like
- 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
- How to Change Font with HTML
- How to Change the Font Size of Text
- How to Change the Font-weight of Text
- How to Change the Font Style of Text
- How to Change the Font Family of Text
- Conclusion
Как установить стиль шрифта. CSS-свойство font
Свойство font используется для оформления текста на сайте. Оно позволяет задавать различные атрибуты шрифта: размер, начертание, жирность, стиль и цвет.
Свойство в общем виде записывается так:
font-family — устанавливает семейство шрифтов.
font-style — задаёт стиль шрифта.
font-variant — определяет вариант шрифта.
font-weight — задаёт жирность шрифта.
font-size — указывает размер шрифта.
line-height — задаёт высоту строки.
Значения и примеры использования
Font-family
В значении свойства font-family указывается список названий шрифтов, перечисленных через запятую. В начале списка располагают самый желаемый шрифт, затем альтернативный, а в самом конце списка — общий тип шрифта. Браузер проходит по списку слева направо и использует первый найденный в системе или на сайте шрифт.
Font-style
Можно выбрать один из стилей оформления текста: обычный шрифт normal , курсив italic , наклонный oblique .
Font-variant
У свойства font-variant несколько значений:
small-caps — все строчные символы отображаются как заглавные уменьшенного размера.
Font-weight
Насыщенность шрифта можно определить числовым значением от 100 до 900 или ключевым словом, например, обычный шрифт normal , полужирный bold .
Возможные значения font-weight :
- 100: Thin;
- 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).
Но в большинстве системных шрифтов есть только два варианта толщины: обычный normal (400) и полужирный bold (700).
Font-size
Размер шрифта font-size измеряется в пикселях ( px ), процентах, относительных ( em , rem ) или абсолютных единицах ( pt , cm , mm ).
Абсолютную величину шрифта можно задавать не только в пикселях, пунктах или других величинах, но и особыми ключевыми словами: xx-small , x-small , small , medium , large , x-large и xx-large . Подробно об этих ключевых словах можно узнать в спецификации.
Line-height
Свойство line-height устанавливает высоту строки, указывая множитель относительно размера шрифта. По умолчанию line-height имеет значение normal . Оно указывает браузеру, что межстрочный интервал нужно подобрать автоматически, исходя из размера шрифта.
Наследование
Свойство font наследуется от родительского элемента на его дочерние элементы.
Нюансы
✅ Если заданы различные атрибуты шрифта в разных правилах для одного элемента, последнее применённое свойство переопределит предыдущие.
✅ Если указанное семейство шрифтов не доступно на устройстве пользователя, браузер будет искать и использовать следующий указанный шрифт из списка или использовать шрифт по умолчанию.
⭐ Свойство font поддерживается современными браузерами. Актуальная информация — на caniuse.com.
Чем заменить свойство font
Если нужно управлять отдельными атрибутами шрифта, например, размером, начертанием, жирностью, можно использовать соответствующие отдельные свойства — font-size , font-style и font-weight .
Материалы по теме
«Доктайп» — журнал о фронтенде. Читайте, слушайте и учитесь с нами.
How to Change a Webpage Text Font and Color Using CSS
wikiHow is a “wiki,” similar to Wikipedia, which means that many of our articles are co-written by multiple authors. To create this article, 16 people, some anonymous, worked to edit and improve it over time.
This article has been viewed 30,551 times.
Do you want to use the newest technology to style your web pages? Here’s how!
To set an order of preference, in case a particular font is not on a person’s computer, use commas to separate font names. For example:
will cause «Text» to use the Times font. If times is not available, Georgia will be used. If neither Times nor Georgia are available, a generic serif font will be used.
will cause «Text» to be red. You can use any valid HTML color name in the place of «red.» You can also use a hex code. For example:
Expert Q&A
Make sure all quotes, colons, and other symbols are in the correct places; otherwise, you may not receive an expected result.
You may want to test your code in multiple browsers, to make sure that it works in as many as possible.
You Might Also Like
How to Insert a Hyperlink Using Rich Text or HTML: 3 Methods
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;
>
How to Change Font with HTML
Kolade Chris
Back in the days of HTML4, there was a tag you could use to change the font size, font family, and the color of a text.
But with HTML5, the tag has been deprecated. So if you want to change anything related to the font, you have to do it with CSS.
In this article, I will show you how to change the font size, font weight, font style, and font family of text using CSS.
How to Change the Font Size of Text
The font size of text represents how big that text is.
To change the font size of some text, you need to use the font-size property and then specify the value in pixels ( px ), rem , or em .
You can do it using inline CSS like this:
You can also do it in embedded or internal CSS:
And finally you can do it in external CSS:
To get rid of the default white background and center the text both horizontally and vertically, I wrote this CSS:
In the browser, it looks as shown below:
How to Change the Font-weight of Text
Font-weight is the property that helps set how bold or light specific text will be.
You can use font-weight to change the lightness or boldness of text, then give it a value such as normal , lighter , bold , or bolder . You can also use values like 100, 200, 500, and so on.
Just like font size, you can change the font-weight in inline, embedded, or external CSS.
freeCodeCamp Lighter freeCodeCamp Normal freeCodeCamp Bold freeCodeCamp Bolder
.lighter < font-weight: lighter; >.normal < font-weight: normal; >.bold < font-weight: bold; >.bolder
.lighter < font-weight: lighter; >.normal < font-weight: normal; >.bold < font-weight: bold; >.bolder
How to Change the Font Style of Text
Font style is the typeface variation of the text. This typeface variation could be normal , bold , or italic .
To change the font style, you need the font-style property with a value of normal , oblique , or italic .
Normal is the default font style, so you don’t need to specify it unless you have to override it.
As usual, you can change the font style in inline, internal, or external CSS.
freeCodeCamp Normal
freeCodeCamp Oblique freeCodeCamp Italic
Here’s the output in the browser:
How to Change the Font Family of Text
A font family represents a collection of fonts that share the same design and typography.
To change the font family of some text, you need to use the CSS font-family property.
You can then choose to do it with inline CSS, internal CSS, or external CSS.
The code snippet below shows how to change the font-family in inline CSS:
freeCodeCamp You can change the font-family in embedded or internal CSS this way: ```css h1
In an external CSS file you can change the font family like this:
Make sure the external CSS is linked to the HTML file, otherwise it won’t work.
The Verdana font family looks like this inside the Google Chrome browser:
You might have noticed that there are other font families in the value – Geneva, Tahoma, and sans-serif.
Those are fallbacks the browser can use in case Verdana is not available on the user’s device.
If you don’t like the fonts built into your device, you can get other ones from Google Fonts.
Search for your favorite font and copy the link to it, then paste the link in the section of your HTML so you can have access to it in your HTML stylesheet
In my case, I used the Roboto font like this:
And this is how it looks in the browser:
Conclusion
This article walked you through how to change the font size, font weight, font style, and font family of text in inline, internal, or external CSS.
You might be wondering which is best to use between inline, internal, or external CSS.
If you’re working on a small project, you can use internal or embedded CSS, but if you’re working on a big project or in a team, you should not use internal CSS.
This is because it is a best practice to keep your CSS away from your HTML.
Inline CSS is a no-no in most situations because it might affect the readability of your HTML.
It’s also been suggested that inline CSS can negatively affect the SEO of a website.