- box-sizing
- Try it
- Syntax
- Values
- Formal definition
- Formal syntax
- Examples
- Box sizes with content-box and border-box
- HTML
- CSS
- Result
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- CSS Box Model
- Example
- Width and Height of an Element
- Example
- Блоки
- Размеры блока
- content-box
- border-box
- Пример
- Эластичные поля ввода
- Резюмирую
- Дальнейшее чтение
box-sizing
The box-sizing CSS property sets how the total width and height of an element is calculated.
Try it
By default in the CSS box model, the width and height you assign to an element is applied only to the element’s content box. If the element has any border or padding, this is then added to the width and height to arrive at the size of the box that’s rendered on the screen. This means that when you set width and height , you have to adjust the value you give to allow for any border or padding that may be added. For example, if you have four boxes with width: 25%; , if any has left or right padding or a left or right border, they will not by default fit on one line within the constraints of the parent container.
The box-sizing property can be used to adjust this behavior:
- content-box gives you the default CSS box-sizing behavior. If you set an element’s width to 100 pixels, then the element’s content box will be 100 pixels wide, and the width of any border or padding will be added to the final rendered width, making the element wider than 100px.
- border-box tells the browser to account for any border and padding in the values you specify for an element’s width and height. If you set an element’s width to 100 pixels, that 100 pixels will include any border or padding you added, and the content box will shrink to absorb that extra width. This typically makes it much easier to size elements. box-sizing: border-box is the default styling that browsers use for the , , and elements, and for elements whose type is radio , checkbox , reset , button , submit , color , or search .
Note: It is often useful to set box-sizing to border-box to lay out elements. This makes dealing with the sizes of elements much easier, and generally eliminates a number of pitfalls you can stumble on while laying out your content. On the other hand, when using position: relative or position: absolute , use of box-sizing: content-box allows the positioning values to be relative to the content, and independent of changes to border and padding sizes, which is sometimes desirable.
Syntax
box-sizing: border-box; box-sizing: content-box; /* Global values */ box-sizing: inherit; box-sizing: initial; box-sizing: revert; box-sizing: revert-layer; box-sizing: unset;
The box-sizing property is specified as a single keyword chosen from the list of values below.
Values
This is the initial and default value as specified by the CSS standard. The width and height properties include the content, but does not include the padding, border, or margin. For example, .box renders a box that is 370px wide.
Here, the dimensions of the element are calculated as: width = width of the content, and height = height of the content. (Borders and padding are not included in the calculation.)
The width and height properties include the content, padding, and border, but do not include the margin. Note that padding and border will be inside of the box. For example, .box renders a box that is 350px wide, with the area for content being 330px wide. The content box can’t be negative and is floored to 0, making it impossible to use border-box to make the element disappear.
Here the dimensions of the element are calculated as: width = border + padding + width of the content, and height = border + padding + height of the content.
Formal definition
Formal syntax
Examples
Box sizes with content-box and border-box
This example shows how different box-sizing values alter the rendered size of two otherwise identical elements.
HTML
div class="content-box">Content boxdiv> br /> div class="border-box">Border boxdiv>
CSS
div width: 160px; height: 80px; padding: 20px; border: 8px solid red; background: yellow; > .content-box box-sizing: content-box; /* Total width: 160px + (2 * 20px) + (2 * 8px) = 216px Total height: 80px + (2 * 20px) + (2 * 8px) = 136px Content box width: 160px Content box height: 80px */ > .border-box box-sizing: border-box; /* Total width: 160px Total height: 80px Content box width: 160px - (2 * 20px) - (2 * 8px) = 104px Content box height: 80px - (2 * 20px) - (2 * 8px) = 24px */ >
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 18, 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.
CSS Box Model
In CSS, the term «box model» is used when talking about design and layout.
The CSS box model is essentially a box that wraps around every HTML element. It consists of: margins, borders, padding, and the actual content. The image below illustrates the box model:
Explanation of the different parts:
- Content — The content of the box, where text and images appear
- Padding — Clears an area around the content. The padding is transparent
- Border — A border that goes around the padding and content
- Margin — Clears an area outside the border. The margin is transparent
The box model allows us to add a border around elements, and to define space between elements.
Example
Demonstration of the box model:
Width and Height of an Element
In order to set the width and height of an element correctly in all browsers, you need to know how the box model works.
Important: When you set the width and height properties of an element with CSS, you just set the width and height of the content area. To calculate the full size of an element, you must also add padding, borders and margins.
Example
This element will have a total width of 350px:
320px (width)
+ 20px (left + right padding)
+ 10px (left + right border)
+ 0px (left + right margin)
= 350px
The total width of an element should be calculated like this:
Total element width = width + left padding + right padding + left border + right border + left margin + right margin
The total height of an element should be calculated like this:
Total element height = height + top padding + bottom padding + top border + bottom border + top margin + bottom margin
Блоки
В CSS блочная модель описывает прямоугольные блоки, которые образуются для элементов, размещённых на странице.
По сути, всё это является прямоугольником.
Некоторые интересные факты:
- border-radius скругляет внешние уголки этого блока;
- box-shadow добавляет тень к этому блоку;
- outline и box-shadow не являются частью блока и, соответственно, не влияют на макет.
Размеры блока
Свойство box-sizing позволяет вам немного управлять моделью, применяемой для задания размеров блоков. Два возможных значения — это content-box и border-box .
content-box
По умолчанию. При вычислении размера блока добавляются padding и border .
border-box
При вычислении размера блока padding и border не учитываются.
Пример
Оба блока содержат одинаковый CSS, но у одного значение box-sizing установлено как content-box , а другого — border-box .
Вид блоков с разным значением box-sizing показан ниже.
В случае border-box ширина и высота .box равны 5em, именно то, что мы задали. В случае content-box ширина и высота равны 7.5em = 5+(2*1)+(2*.25) , поскольку мы добавляем padding и border с каждой стороны.
Эластичные поля ввода
Одним из преимуществ применения border-box — это возможность установить отступы и ширину в разных единицах, без крайних случаев. Одним из фантастических примеров использования этого является создание эластичных полей ввода с фиксированным padding .
В приведённом ниже примере, у input задан определённый padding в единицах em и при этом мы ещё можем указать ширину в процентах ( padding: .4em .55em и width: 100% , соответственно).
Настройте ширину блока и следите за размерами самого поля, который прекрасно располагается внутри блока, сохраняя фиксированный padding .
Резюмирую
Если вы хотите получить высоту и ширину, которая ведёт себя интуитивно понятным образом, послушайте Пола Ириша и вставьте это в верхнюю часть своего CSS: