- CSS values and units
- Textual data types
- Pre-defined keyword values
- CSS-wide values
- URLs
- Numeric data types
- Integers
- Numbers
- Dimensions
- Distance units
- Angle units
- Time units
- Frequency units
- Flex units
- Resolution units
- Percentages
- Mixing percentages and dimensions
- Единицы измерения в CSS: px, rem, em, fr, %
- Варианты единиц измерения
- px
- rem
- em
- fr
- Для чего использовать
- px
- rem и em
- fr
- Материалы по теме
CSS values and units
Every CSS declaration includes a property / value pair. Depending on the property, the value can include a single integer or keyword, to a series of keywords and values with or without units. There are a common set of data types — values and units — that CSS properties accept. Below is an overview of most of these data types. Refer to the page for each value type for more detailed information.
Textual data types
Text data types are either , a quoted series of characters, or an , a «CSS Identifier» which is an unquoted string. A must be quoted with either single or double quotes. CSS Identifiers, listed in the specifications as or , must be unquoted.
In the CSS specifications, values that can be defined by the web developer, like keyframe animations, font-family names, or grid areas are listed as a , , or both.
When both quoted and unquoted user defined text values are permitted, the specification will list | , meaning quotes are optional, such as is the case with animation names:
@keyframe validIdent /* keyframes go here */ > @keyframe 'validString' /* keyframes go here */ >
Some text values are not valid if encompassed in quotes. For example, the value of grid-area can be a , so if we had a grid area named content we would use it without quotes:
In comparison, a data type that is a , such as a string value of the content property, must be quoted:
.item::after content: "This is my content."; >
While you can generally create any name you want, including using emojis, the identifier can’t be none , unset , initial , or inherit , start with a digit or two dashes, and generally you don’t want it to be any other pre-defined CSS keyword. See the and reference pages for more details.
Pre-defined keyword values
Pre-defined keywords are text values defined by the specification for that property. These keywords are also CSS Identifiers and are therefore used without quotes.
When viewing CSS property value syntax in a CSS specification or the MDN property page, allowable keywords will be listed in the following form. The following values are the pre-defined keyword values allowed for float .
left | right | none | inline-start | inline-end
Such values are used without quotes:
CSS-wide values
In addition to the pre-defined keywords that are part of the specification for a property, all CSS properties accept the CSS-wide property values initial , inherit , unset , revert , and revert-layer , which explicitly specify defaulting behaviors.
Represents the value specified as the property’s initial value.
Represents the computed value of the property on the element’s parent, provided it is inherited.
Acts as either inherit or initial , depending on whether the property is inherited or not.
Resets the property to its inherited value if it inherits from its parent or to the default value established by the user agent’s stylesheet (or by user styles, if any exist).
Rolls back the value of a property in a cascade layer to the value of the property in a CSS rule matching the element in a previous cascade layer. The value of the property with this keyword is recalculated as if no rules were specified on the target element in the current cascade layer.
URLs
A url() type uses functional notation, which accepts a that is a URL. This may be an absolute URL or a relative URL. For example, if you wanted to include a background image, you might use either of the following.
.box background-image: url("images/my-background.png"); > .box background-image: url("https://www.exammple.com/images/my-background.png"); >
The parameter for url() can be either quoted or unquoted. If unquoted, it is parsed as a , which has extra requirements including the escaping of certain characters. See url() for more information.
Numeric data types
Integers
An integer is one or more decimal digits, 0 through 9 , such as 1024 or -55 . An integer may be preceded by a + or — symbol, with no space between the symbol and the integer.
Numbers
Dimensions
CSS uses dimensions to specify:
These are all covered in subsections below.
Distance units
Where a distance unit, also known as a length, is allowed as a value for a property, this is described as the type. There are two types of lengths in CSS: relative and absolute.
Relative length units specify a length in relation to something else. For example, em is relative to the font size on the element and vh is relative to the viewport height.
Unit | Relative to |
---|---|
em | Font size of the element. |
ex | x-height of the element’s font. |
cap | Cap height (the nominal height of capital letters) of the element’s font. |
ch | Average character advance of a narrow glyph in the element’s font, as represented by the «0» (ZERO, U+0030) glyph. |
ic | Average character advance of a full width glyph in the element’s font, as represented by the «水» (CJK water ideograph, U+6C34) glyph. |
rem | Font size of the root element. |
lh | Line height of the element. |
rlh | Line height of the root element. |
vw | 1% of viewport’s width. |
vh | 1% of viewport’s height. |
vi | 1% of viewport’s size in the root element’s inline axis. |
vb | 1% of viewport’s size in the root element’s block axis. |
vmin | 1% of viewport’s smaller dimension. |
vmax | 1% of viewport’s larger dimension. |
Container query length units specify a length relative to the dimensions of a query container. For example, cqw is relative to the width of the query container and cqh is relative to the height of the query container.
Unit | Relative to |
---|---|
cqw | 1% of a query container’s width |
cqh | 1% of a query container’s height |
cqi | 1% of a query container’s inline size |
cqb | 1% of a query container’s block size |
cqmin | The smaller value of cqi or cqb |
cqmax | The larger value of cqi or cqb |
Absolute length units are fixed to a physical length: either an inch or a centimeter. Many of these units are therefore more useful when the output is a fixed size media, such as print. For example, mm is a physical millimeter, 1/10th of a centimeter.
Unit | Name | Equivalent to |
---|---|---|
cm | Centimeters | 1cm = 96px/2.54 |
mm | Millimeters | 1mm = 1/10th of 1cm |
Q | Quarter-millimeters | 1Q = 1/40th of 1cm |
in | Inches | 1in = 2.54cm = 96px |
pc | Picas | 1pc = 1/6th of 1in |
pt | Points | 1pt = 1/72th of 1in |
px | Pixels | 1px = 1/96th of 1in |
When including a length value, if the length is 0 , the unit identifier is not required. Otherwise, the unit identifier is required, is case insensitive, and must come immediately after the numeric part of the value, with no space in-between.
Angle units
Angle values are represented by the type and accept the following values:
Unit | Name | Description |
---|---|---|
deg | Degrees | There are 360 degrees in a full circle. |
grad | Gradians | There are 400 gradians in a full circle. |
rad | Radians | There are 2π radians in a full circle. |
turn | Turns | There is 1 turn in a full circle. |
Time units
Unit | Name | Description |
---|---|---|
s | Seconds | |
ms | Milliseconds | There are 1,000 milliseconds in a second. |
Frequency units
Frequency values are represented by the type . It accepts the following values.
Unit | Name | Description |
---|---|---|
Hz | Hertz | Represents the number of occurrences per second. |
kHz | KiloHertz | A kiloHertz is 1000 Hertz. |
1Hz , which can also be written as 1hz or 1HZ , is one cycle per second.
Flex units
Flex units are represented by the type . It accepts the following value.
Unit | Name | Description |
---|---|---|
fr | Flex | Represents a flexible length within a grid container |
Resolution units
Unit | Description |
---|---|
dpi | Dots per inch. |
dpcm | Dots per centimeter. |
dppx , x | Dots per px unit. |
Percentages
Percentage values are always relative to another quantity, for example a length. Each property that allows percentages also defines the quantity to which the percentage refers. This quantity can be a value of another property of the same element, the value of a property of an ancestor element, a measurement of a containing block, or something else.
As an example, if you specify the width of a box as a percentage, it refers to the percentage of the box’s parent’s computed width:
Mixing percentages and dimensions
Some properties accept a dimension that could be either one of two types, for example a or a . In this case the allowed value is detailed in the specification as a combination unit, e.g. . Other possible combinations are as follows:
Единицы измерения в CSS: px, rem, em, fr, %
Единицы измерения в CSS используют для определения размеров элементов, расстояний, шрифтов и других свойств. В статье расскажем про пять единиц измерения: px , em , rem , fr , % . Они делятся на абсолютные и относительные. Давайте разбираться, чем они отличаются.
💡 Абсолютные единицы измерения привязаны к настоящим физическим размерам.
Познакомиться со всеми абсолютными единицами измерения можно в спецификации. Среди них пиксели, сантиметры, миллиметры, дюймы и непривычные нам единицы измерения вроде одной сороковой доли сантиметра.
💡 Относительные единицы измерения описывают значения, которые зависят от других значений.
Познакомиться со всеми относительными единицами измерения можно в спецификации. Среди них em , rem , vh , ex и другие единицы измерения.
Варианты единиц измерения
px
Пиксель бывает физическим и CSS-пикселем.
Физический пиксель — это пиксель на матрице девайса. Например, когда мы говорим, что ширина экрана устройства 480px , то подразумеваем, что по всей ширине находится 480 неделимых ячеек, где 1px равен одной ячейке.
CSS-пиксель — это единица измерения CSS, равная 1/96 части дюйма. Один пиксель не всегда равен одной ячейке на экране. Это зависит от плотности экрана, чем больше физических пикселей на экране, тем выше его плотность и тем детальнее выводимое на него изображение. Подробнее рассказали в статье «Как подготовить вёрстку к retina-экранам».
Пример использования
rem
Единица измерения, которая зависит от размера шрифта корневого элемента в документе — обычно . Значение 1rem соответствует размеру шрифта корневого элемента. Например, если в теге задан шрифт 16px , то для всех вложенных в него элементов font-size: 1.5rem; установит размер шрифта в 24px .
Пример использования
em
Единица измерения, которая задаёт размер шрифта равный родительскому элементу. Например, если у родительского элемента размер шрифта равен 16px , то font-size: 1.5em; установит размер шрифта дочернего элемента в 24px .
Пример использования
Для значение 2em означает, что размер шрифта будет в два раза больше, чем размер шрифта элемента-родителя.
Проценты задают размер относительно родительского элемента. Родительский элемент равен 100% , тогда width: 50%; будет равна половине ширины родительского элемента.
Пример использования
Контейнер занимает 80% ширины родительского элемента, а блок-коробка занимает 50% ширины контейнера.
fr
Доля свободного пространства — относительная единица измерения, которая используется в CSS Grid для распределения доступного пространства между ячейками. Свободное пространство в родительском элементе делится на равные доли — fr , а дочерние элементы распределяют пространство между собой. На примере мы покажем, как пространство делится между элементами.
Пример использования
Для чего использовать
px
- Задаёт ширину и высоту элементов: width: 200px; , height: 100px; .
- Задаёт отступы и поля: margin: 10px; , padding: 20px; .
- Задаёт размер шрифта: font-size: 16px; .
rem и em
- Задаёт размер шрифта: font-size: 1.5rem; , font-size: 1.2em; .
- Задаёт отступы и полей с учетом размера шрифта: margin: 0.5rem; , padding: 0.8em; .
- Задаёт размер элементов относительно размеров родительского элемента: width: 50%; , height: 75%; .
- Задаёт отступы и поля относительно размеров родительского элемента: margin: 10%; , padding: 5%; .
fr
- Используется для распределения доступного пространства между ячейками сетки: grid-template-columns: 1fr 2fr; — распределит доступное пространство между двумя колонками в соотношении 1:2.
- Используется для распределения пространства между элементами в гибком контейнере: flex: 1fr; — распределит доступное пространство между элементами в контейнере.
Материалы по теме
«Доктайп» — журнал о фронтенде. Читайте, слушайте и учитесь с нами.