- Форматирование текста (font-weight, font-style, font-size, text-indent) в HTML
- Курсив (font-style)
- Размер шрифта (font-size)
- Красная строка (text-indent)
- font-weight
- Try it
- Syntax
- Values
- Fallback weights
- Meaning of relative weights
- Common weight name mapping
- Variable fonts
- Accessibility concerns
- Formal definition
- Formal syntax
- Examples
- Setting font weights
- HTML
- CSS
- Result
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- 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
Форматирование текста (font-weight, font-style, font-size, text-indent) в HTML
Помимо эти названий свойство font-weight может принимать численные значения: 100, 200, 300, 400 и т.д. до 900. Чем больше цифра — тем жирнее текст. Нормальный текст без выделения жирным соответствует цифре 400. Выделенный жирным текст соответствует цифре 700.
Далеко не у всех шрифтов есть весь набор градаций жирного. Обычно используются только два: bold и normal варианты. Поэтому в таких ситуациях какую цифру ни ставь, все равно получишь только 2 варианта жирности. Но через CSS можно подключить шрифты (указать адреса файлов), в которых будет все остальные градации жирности.
Курсив (font-style)
Курсив можно получить с помощью тега . Но ещё и через свойство font-style со значением italic. Приведём пример:
Размер шрифта (font-size)
- px — пикселы,
- % — проценты (от размера шрифта родительского элемента)
- em — высота шрифта элемента (единица — это сто процентов от размера шрифта родительского элемента),
- pt — пункты (по сути пиксели, но в пропорции 12pt = 16px)
- текстовые названия размеров: xx-small, x-small, smal, medium, large, x-large, xx-large
- ex — высота символа х (единица — это сто процентов),
Тише, мыши, кот на крыше. Тише, мыши, кот на крыше. Тише, мыши, кот на крыше. Тише, мыши, кот на крыше. Тише, мыши, кот на крыше. Тише, мыши, кот на крыше.
Тише, мыши, кот на крыше. Тише, мыши, кот на крыше. Тише, мыши, кот на крыше. Тише, мыши, кот на крыше. Тише, мыши, кот на крыше. Тише, мыши, кот на крыше. Тише, мыши, кот на крыше.
Красная строка (text-indent)
Наверное, вы уже заметили, что HTML не воспринимает пробелы. То есть если в HTML коде поставить сотню пробелов между словами, а потом открыть этот HTML файл в браузере, то пробелы заменятся на один. Из-за этого и нет возможности сделать красную строку в абзаце. Но на помощь приходит CSS свойство text-indent, которое может сделать этот отступ. Значение этого свойства задаются в пикселях. Приведём пример:
Тише, мыши, кот на крыше,
а котята ещё выше.
font-weight
The font-weight CSS property sets the weight (or boldness) of the font. The weights available depend on the font-family that is currently set.
Try it
Syntax
/* Keyword values */ font-weight: normal; font-weight: bold; /* Keyword values relative to the parent */ font-weight: lighter; font-weight: bolder; /* Numeric keyword values */ font-weight: 100; font-weight: 200; font-weight: 300; font-weight: 400; /* normal */ font-weight: 500; font-weight: 600; font-weight: 700; /* bold */ font-weight: 800; font-weight: 900; /* Global values */ font-weight: inherit; font-weight: initial; font-weight: revert; font-weight: revert-layer; font-weight: unset;
The font-weight property is specified using any one of the values listed below.
Values
Normal font weight. Same as 400 .
Bold font weight. Same as 700 .
One relative font weight lighter than the parent element. Note that only four font weights are considered for relative weight calculation; see the Meaning of relative weights section below.
One relative font weight heavier than the parent element. Note that only four font weights are considered for relative weight calculation; see the Meaning of relative weights section below.
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 using the Fallback weights system.
CSS Fonts Level 4 extends the syntax to accept any number between 1 and 1000 and introduces Variable fonts, which can make use of this much finer-grained range of font weights.
Fallback weights
If the exact weight given is unavailable, then the following rule is used to determine the weight actually rendered:
- If the target weight given is between 400 and 500 inclusive:
- Look for available weights between the target and 500 , in ascending order.
- If no match is found, look for available weights less than the target, in descending order.
- If no match is found, look for available weights greater than 500 , in ascending order.
Meaning of relative weights
When lighter or bolder is specified, the below chart shows how the absolute font weight of the element is determined.
Note that when using relative weights, only four font weights are considered — thin (100), normal (400), bold (700), and heavy (900). If a font-family has more weights available, they are ignored for the purposes of relative weight calculation.
Inherited value bolder lighter 100 400 100 200 400 100 300 400 100 400 700 100 500 700 100 600 900 400 700 900 400 800 900 700 900 900 700 Common weight name mapping
The numerical values 100 to 900 roughly correspond to the following common weight names (see the OpenType specification):
Value Common weight name 100 Thin (Hairline) 200 Extra Light (Ultra Light) 300 Light 400 Normal (Regular) 500 Medium 600 Semi Bold (Demi Bold) 700 Bold 800 Extra Bold (Ultra Bold) 900 Black (Heavy) 950 Extra Black (Ultra Black) 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 a 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 widths.
Note: For the example below to work, you’ll need a browser that supports the CSS Fonts Level 4 syntax in which font-weight can be any number between 1 and 1000 . The demo loads with font-weight: 500; . Change the value to see the weight of the text change.
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
Initial value normal Applies to all elements. It also applies to ::first-letter and ::first-line . Inherited yes Computed value the keyword or the numerical value as specified, with bolder and lighter transformed to the real value Animation type a font weight Formal syntax
font-weight =
|
bolder |
lighter=
normal |
bold |Examples
Setting font weights
HTML
p> Alice was beginning to get very tired of sitting by her sister on the bank, and of having nothing to do: once or twice she had peeped into the book her sister was reading, but it had no pictures or conversations in it, "and what is the use of a book," thought Alice "without pictures or conversations?" p> div> I'm heavybr /> span>I'm lighterspan> div>
CSS
/* Set paragraph text to be bold. */ p font-weight: bold; > /* Set div text to two steps heavier than normal but less than a standard bold. */ div font-weight: 600; > /* Set span text to be one step lighter than its parent. */ span font-weight: lighter; >
Result
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 26, 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.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.