Font size normal css

Как установить стиль шрифта. 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 наследуется от родительского элемента на его дочерние элементы.

Нюансы

✅ Если заданы различные атрибуты шрифта в разных правилах для одного элемента, последнее применённое свойство переопределит предыдущие.

Для второго абзаца заданы сначала общие параметры, а затем переопределены в селекторе по классу

✅ Если указанное семейство шрифтов не доступно на устройстве пользователя, браузер будет искать и использовать следующий указанный шрифт из списка или использовать шрифт по умолчанию.

Шрифт PT Sans Regular недоступен, поэтому заголовок оформлен шрифтом Arial

⭐ Свойство font поддерживается современными браузерами. Актуальная информация — на caniuse.com.

Чем заменить свойство font

Если нужно управлять отдельными атрибутами шрифта, например, размером, начертанием, жирностью, можно использовать соответствующие отдельные свойства — font-size , font-style и font-weight .

Материалы по теме

«Доктайп» — журнал о фронтенде. Читайте, слушайте и учитесь с нами.

Источник

font-size

CSS Свойство font-size определяет размер шрифта. Это свойство также используется для вычисления размера em , ex и других относительных единиц. Подробнее: .

Читайте также:  Random Color Generator

Интерактивный пример

Синтаксис

/* значения в */ font-size: xx-small; font-size: x-small; font-size: small; font-size: medium; font-size: large; font-size: x-large; font-size: xx-large; /* значения в */ font-size: larger; font-size: smaller; /* */ font-size: 12px; font-size: 0.8em; /* */ font-size: 80%; /* Глобальные значения */ font-size: inherit; font-size: initial; font-size: unset; 

Свойство font-size устанавливается одним из следующих способов:

  • Ключевым словом из перечня абсолютных значений или относительных значений
  • Как или , по отношению к размеру родительского элемента.

Значения

Набор ключевых слов абсолютных значений, по отношению к пользовательскому размеру шрифта по умолчанию (им считается medium — среднее).

Больше (larger) или меньше (smaller). Ключевые слова для относительного размера. Шрифт будет больше или меньше по отношению в размеру шрифта родительского элемента.Примерно на такое же соотношение, которое используется в ключевых словах абсолютного размера выше.

Примечание: Для обеспечения максимальной совместимости обычно лучше использовать значения, относящиеся к размеру шрифта пользователя по умолчанию.

Формальный синтаксис

font-size =
| (en-US)
| (en-US)
(en-US) | (en-US)
math

=
| (en-US)

Возможные подходы

Существуют разные способы задания размера шрифта. С помощью ключевых слов или с помощью числовых значений для размера пикселей или размера ems. Выберите подходящий метод в зависимости от потребностей конкретной веб-страницы.

Ключевые слова

Keywords are a good way to set the size of fonts on the web. By setting a keyword font size on the body element, you can set relative font-sizing everywhere else on the page, giving you the ability to easily scale the font up or down on the entire page accordingly.

Pixels

Setting the font size in pixel values ( px ) is a good choice when you need pixel accuracy. A px value is static. This is an OS-independent and cross-browser way of literally telling the browsers to render the letters at exactly the number of pixels in height that you specified. The results may vary slightly across browsers, as they may use different algorithms to achieve a similar effect.

Font sizing settings can also be used in combination. For example, if a parent element is set to 16px and its child element is set to larger , the child element displays larger than the parent element in the page.

Примечание: Defining font sizes in pixel is not accessible, because the user cannot change the font size from the browser. (For example, users with limited vision may wish to set the font size much larger than the size chosen by a web designer.) Therefore, avoid using pixels for font sizes if you wish to create an inclusive design.

Ems

Another way of setting the font size is with em values. The size of an em value is dynamic. When defining the font-size property, an em is equal to the size of the font that applies to the parent of the element in question. If you haven’t set the font size anywhere on the page, then it is the browser default, which is probably 16px. So, by default 1em = 16px, and 2em = 32px. If you set a font-size of 20px on the body element, then 1em = 20px and 2em = 40px. Note that the value 2 is essentially a multiplier of the current em size.

Читайте также:  Html table группировка строк

In order to calculate the em equivalent for any pixel value required, you can use this formula:

em = desired element pixel value / parent element font-size in pixels

For example, suppose the font-size of the body of the page is set to 1em, with the browser standard of 1em = 16px; if the font-size you want is 12px, then you should specify 0.75em (because 12/16 = 0.75). Similarly, if you want a font size of 10px, then specify 0.625em (10/16 = 0.625); for 22px, specify 1.375em (22/16).

A popular technique to use throughout the document is to set the the font-size of the body to 62.5% (that is 62.5% of the default of 16px), which equates to 10px, or 0.625em. Now you can set the font-size for any elements using em units, with an easy-to-remember conversion, by dividing the px value by 10. This way 6px = 0.6em, 8px = 0.8em, 12px = 1.2em, 14px = 1.4em, 16px = 1.6em. For example:

body  font-size: 62.5%; /* font-size 1em = 10px on default browser settings */ > span  font-size: 1.6em; /* 1.6em = 16px */ > 

The em is a very useful unit in CSS, since it automatically adapts its length relative to the font that the reader chooses to use.

One important fact to keep in mind: em values compound. Take the following HTML and apply it with the previous CSS above:

div> span>Outer span>innerspan> outerspan> div> 

Assuming that the browser’s default font-size is 16px, the words «outer» would be rendered at 16px, but the word «inner» would be rendered at 25.6px. This is because the inner span’s font-size is 1.6 em which is relative to its parent’s font-size , which is in turn relative to its parent’s font-size . This is often called compounding.

Rems

rem values were invented in order to sidestep the compounding problem. rem values are relative to the root html element, not the parent element. In other words, it lets you specify a font size in a relative fashion without being affected by the size of the parent, thereby eliminating compounding.

The CSS below is nearly identical to the previous example. The only exception is that the unit has been changed to rem .

html  font-size: 62.5%; /* font-size 1em = 10px on default browser settings */ > span  font-size: 1.6rem; > 

Then we apply this CSS to the same HTML, which looks like this:

span>Outer span>innerspan> outerspan> 

In this example, the words «outer inner outer» are all displayed at 16px (assuming that the browser’s font-size has been left at the default value of 16px).

Примеры

Пример 1

/* Set paragraph text to be very large. */ p  font-size: xx-large > /* Set h1 (level 1 heading) text to be 2.5 times the size * of the text around it. */ h1  font-size: 250% > /* Sets text enclosed within span tag to be 16px */ span  font-size: 16px; > 

Пример 2

.small  font-size: xx-small; > .larger  font-size: larger; > .point  font-size: 24pt; > .percent  font-size: 200%; > 
h1 class="small">Small H1h1> h1 class="larger">Larger H1h1> h1 class="point">24 point H1h1> h1 class="percent">200% H1h1> 

Live Sample

Примечание

em and ex units on the font-size property are relative to the parent element’s font size (unlike all other properties, where they’re relative to the font size on the element). This means em units and percentages do the same thing for font-size .

Спецификации

Совместимость браузеров

BCD tables only load in the browser

Found a content problem with this page?

This page was last modified on 22 февр. 2023 г. by MDN contributors.

Your blueprint for a better internet.

Источник

CSS Font Size

Being able to manage the text size is important in web design. However, you should not use font size adjustments to make paragraphs look like headings, or headings look like paragraphs.

Always use the proper HTML tags, like — for headings and

for paragraphs.

The font-size value can be an absolute, or relative size.

  • Sets the text to a specified size
  • Does not allow a user to change the text size in all browsers (bad for accessibility reasons)
  • Absolute size is useful when the physical size of the output is known
  • Sets the size relative to surrounding elements
  • Allows a user to change the text size in browsers

Note: If you do not specify a font size, the default size for normal text, like paragraphs, is 16px (16px=1em).

Set Font Size With Pixels

Setting the text size with pixels gives you full control over the text size:

Example

Tip: If you use pixels, you can still use the zoom tool to resize the entire page.

Set Font Size With Em

To allow users to resize the text (in the browser menu), many developers use em instead of pixels.

1em is equal to the current font size. The default text size in browsers is 16px. So, the default size of 1em is 16px.

The size can be calculated from pixels to em using this formula: pixels/16=em

Example

h2 font-size: 1.875em; /* 30px/16=1.875em */
>

p font-size: 0.875em; /* 14px/16=0.875em */
>

In the example above, the text size in em is the same as the previous example in pixels. However, with the em size, it is possible to adjust the text size in all browsers.

Unfortunately, there is still a problem with older versions of Internet Explorer. The text becomes larger than it should when made larger, and smaller than it should when made smaller.

Use a Combination of Percent and Em

The solution that works in all browsers, is to set a default font-size in percent for the element:

Example

Our code now works great! It shows the same text size in all browsers, and allows all browsers to zoom or resize the text!

Responsive Font Size

The text size can be set with a vw unit, which means the «viewport width».

That way the text size will follow the size of the browser window:

Hello World

Resize the browser window to see how the font size scales.

Example

Hello World

Viewport is the browser window size. 1vw = 1% of viewport width. If the viewport is 50cm wide, 1vw is 0.5cm.

Источник

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