- calc ( )
- Кратко
- Пример
- Как пишется
- Как понять
- Подсказки
- На практике
- Алёна Батицкая советует
- calc()
- Try it
- Syntax
- Notes
- Formal syntax
- Accessibility concerns
- Usage with integers
- Examples
- Positioning an object on screen with a margin
- Automatically sizing form fields to fit their container
- Nested calc() with CSS Variables
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
calc ( )
Настоящая математика внутри CSS! Что может быть безумнее удобнее?
Время чтения: меньше 5 мин
Обновлено 13 декабря 2021
Кратко
Скопировать ссылку «Кратко» Скопировано
Классная функция, позволяющая производить математические вычисления прямо в CSS. Раньше, до появления calc ( ) , приходилось страдать и вычислять размеры примерно.
Пример
Скопировать ссылку «Пример» Скопировано
Частая ситуация: в вёрстке три колонки, ширина каждой из которых должна быть ровно третью от 100%. 100% / 3 = 33.3333333333. %. Раньше мы допускали неточность и указывали ширину как 33%. Теперь можно использовать calc ( ) и пусть браузер сам считает.
При отрисовке страницы браузер сам высчитает и подставит значение:
.selector width: calc(100% / 3);>
.selector width: calc(100% / 3); >
Но лучше не перегружать браузер расчётами. На каждую операцию он тратит некую долю секунды и часть оперативной памяти. Если расчётов будет много, то это потенциально повлияет на скорость загрузки страницы. Используйте calc ( ) с умом.
Как пишется
Скопировать ссылку «Как пишется» Скопировано
В круглых скобках мы можем писать любые математические операции с любыми единицами измерения, доступными в вебе (%, px, rem, em, vw, vh, vmin и т.д.). Доступны четыре стандартных операнда:
Операторы сложения и вычитания обязательно с двух сторон должны отбиваться пробелом. Иначе браузер воспримет их как часть числа. Хоть операторы деления и умножения не требуют такой строгости к себе, но принято и их тоже отбивать пробелами для удобства чтения.
.selector width: calc(100% - 2rem);>
.selector width: calc(100% - 2rem); >
.selector width: calc(100% -2rem);>
.selector width: calc(100% -2rem); >
Внутри скобок может быть больше одного вычисления, можно группировать операции при помощи скобок. Всё как в настоящем языке программирования 😺 Но не стоит увлекаться: чем короче вычисление, тем проще потом его прочитать и понять что там вообще происходит.
Для каких свойств можно указать calc ( ) в качестве значения? Для любых, значением которых должна быть цифра! Причём если свойство предполагает составное значение, то можно указать функцию как часть этого значения:
.selector margin: calc(5vh / 4) 20px; transition: transform calc(0.5s + 120ms);>
.selector margin: calc(5vh / 4) 20px; transition: transform calc(0.5s + 120ms); >
Внутри круглых скобок можно складывать только числовые значения. Нельзя сложить число со строкой, хотя в полноценных языках программирования, типа JavaScript, такой трюк с лёгкостью бы удался.
Ещё одно неудачное место для этой функции — медиавыражения. Вот такая запись считается не валидной:
@media (min-width: calc(465px + 1vw)) . ;>
@media (min-width: calc(465px + 1vw)) . ; >
Хотя бы у одной из цифр внутри скобок нужно указать единицу измерения, иначе браузер не сможет понять, от чего же вести вычисление.
Как понять
Скопировать ссылку «Как понять» Скопировано
Во время отрисовки (рендеринга) страницы браузер заглядывает в CSS и производит все вычисления из функций calc ( ) , подставляя на их место итоговое значение. Исходя из этих значений и отрисовываются стили элементов.
Подсказки
Скопировать ссылку «Подсказки» Скопировано
💡 Очень удобно (и часто приходится) использовать, когда из одной величины в относительных единицах надо вычесть другую величину в абсолютных единицах. Самостоятельно это никак не посчитать, а браузеру раз плюнуть. Например, каким будет результат такого вычисления?
.selector height: calc(100vh - 34px);>
.selector height: calc(100vh - 34px); >
На практике
Скопировать ссылку «На практике» Скопировано
Алёна Батицкая советует
Скопировать ссылку «Алёна Батицкая советует» Скопировано
🛠 Возьмём тот же пример с тремя колонками из начала статьи. Пусть у каждой из колонок будет внешний отступ по 40 px с каждой из сторон. Если зададим свойства в лоб, то ничего не выйдет, последний блок падает на новую строку.
Газеты
Заводы
Пароходы
div class="parent"> div class="child"> h2>Газетыh2> div> div class="child"> h2>Заводыh2> div> div class="child"> h2>Пароходыh2> div> div>
.child display: inline-block; width: 33.3%; margin-left: 40px; margin-right: 40px;>
.child display: inline-block; width: 33.3%; margin-left: 40px; margin-right: 40px; >
Можно использовать флексбокс. Избежим падения, но получим проблему сужения блоков, чтобы уместиться в ряд. Как всего этого избежать? Высчитывать размер блоков с учётом этих боковых отступов!
.child display: inline-block; width: calc(33.3% - 80px); margin-left: 40px; margin-right: 40px;>
.child display: inline-block; width: calc(33.3% - 80px); margin-left: 40px; margin-right: 40px; >
calc()
The calc() CSS function lets you perform calculations when specifying CSS property values. It can be used with , , , , , , or values.
Try it
Syntax
/* property: calc(expression) */ width: calc(100% - 80px);
The calc() function takes a single expression as its parameter, with the expression’s result used as the value. The expression can be any simple expression combining the following operators, using standard operator precedence rules:
Multiplication. At least one of the arguments must be a .
Division. The right-hand side must be a .
Notes
Serializing the arguments inside calc() follows the IEEE-754 standard for floating point math which means there’s a few cases to be aware of regarding the infinity and NaN constants. For more details on how constants are serialized, see the calc-constant page.
In addition, the following notes apply:
- The + and — operators must be surrounded by whitespace. For instance, calc(50% -8px) will be parsed as «a percentage followed by a negative length» — which is an invalid expression — while calc(50% — 8px) is «a percentage followed by a subtraction operator and a length». Likewise, calc(8px + -50%) is treated as «a length followed by an addition operator and a negative percentage».
- The * and / operators do not require whitespace, but adding it for consistency is recommended.
- Math expressions involving percentages for widths and heights on table columns, table column groups, table rows, table row groups, and table cells in both auto and fixed layout tables may be treated as if auto had been specified.
- It is permitted to nest calc() functions, in which case the inner ones are treated as simple parentheses.
- For lengths, you can’t use 0 to mean 0px (or another length unit); instead, you must use the version with the unit: margin-top: calc(0px + 20px); is valid, while margin-top: calc(0 + 20px); is invalid.
- The calc() function cannot directly substitute the numeric value for percentage types; for instance calc(100 / 4)% is invalid, while calc(100% / 4) is valid.
Formal syntax
=
calc( )
=
[ [ ‘+’ | ‘-‘ ] ]*
=
[ [ ‘*’ | ‘/’ ] ]*
=
|
|
|
|
( )
=
e |
pi |
infinity |
-infinity |
NaN
Accessibility concerns
When calc() is used for controlling text size, be sure that one of the values includes a relative length unit, for example:
h1 font-size: calc(1.5rem + 3vw); >
This ensures that text size will scale if the page is zoomed.
Usage with integers
This will give .modal a final z-index value of 2.
Examples
Positioning an object on screen with a margin
calc() makes it easy to position an object with a set margin. In this example, the CSS creates a banner that stretches across the window, with a 40-pixel gap between both sides of the banner and the edges of the window:
.banner position: absolute; left: 40px; width: calc(100% - 80px); border: solid black 1px; box-shadow: 1px 2px; background-color: yellow; padding: 6px; text-align: center; box-sizing: border-box; >
div class="banner">This is a banner!div>
Automatically sizing form fields to fit their container
Another use case for calc() is to help ensure that form fields fit in the available space, without extruding past the edge of their container, while maintaining an appropriate margin.
input padding: 2px; display: block; width: calc(100% - 1em); > #form-box width: calc(100% / 6); border: 1px solid black; padding: 4px; >
Here, the form itself is established to use 1/6 of the available window width. Then, to ensure that input fields retain an appropriate size, we use calc() again to establish that they should be the width of their container minus 1em. Then, the following HTML makes use of this CSS:
form> div id="form-box"> label for="misc">Type something:label> input type="text" id="misc" name="misc" /> div> form>
Nested calc() with CSS Variables
You can also use calc() with CSS variables. Consider the following code:
.foo --widthA: 100px; --widthB: calc(var(--widthA) / 2); --widthC: calc(var(--widthB) / 2); width: var(--widthC); >
After all variables are expanded, widthC ‘s value will be calc(calc(100px / 2) / 2) , then when it’s assigned to .foo ‘s width property, all inner calc() s (no matter how deeply nested) will be flattened to just parentheses, so the width property’s value will be eventually calc((100px / 2) / 2) , i.e. 25px . In short: a calc() inside of a calc() is identical to just parentheses.
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 18, 2023 by MDN contributors.
Your blueprint for a better internet.