Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

CSS3 box size


May 04, 2021 CSS3


Table of contents


CSS3 box size

The CSS3 box-sizing can set the width and height properties to include padding (inner margin) and border (border).


Browser support

The numbers in the table support the version number of the first browser for this property.

Immediately after the number - webkit - or -moz - is the prefix for the specified browser.

Property
box-sizing 10.0
4.0 -webkit-
8.0 29.0
2.0 -moz-
5.1
3.1 -webkit-
9.5

The CSS3 box-sizing property is not used

By default, the width and height of an element are calculated as follows:

width (wide) and padding (inside margin) and border (border) - the actual width of the element

Height (high) and padding (inside margin) and border (border) - the actual height of the element

This means that when we set the width/height of an element, the height and width of the element's actual presentation is greater (because the element's border and margin are also calculated in width/height).

This is a smaller box (width is 300px and height is 100px).

This is a larger box (width is 300px and height is 100px).

The above two elements, although the width and height settings are the same, do not match the size of the real presentation because div2 specifies an inner margin:

Instance

.div1 {
width: 300px;
height: 100px;
border: 1px solid blue;
}

.div2 {
width: 300px;
height: 100px;
padding: 50px;
border: 1px solid red;
}

Try it out . . .

In this way, if you want to get a smaller box that contains the inner margin, you have to take into account the width of the border and the inner margin.

The box-sizing property of CSS3 solves this problem well.


Use the CSS3 box-sizing property

The CSS3 box-sizing contains padding (inner margin) and border (border) in the width and height of an element.

If box-sizing: border-box; Padding (inner margin) and border (border) are also included in width and height:

Two divs are the same size now!

W3Cschool tutorial!

Here are two elements to add box-sizing: border-box; A simple instance of the property.

Instance

.div1 {
width: 300px;
height: 100px;
border: 1px solid blue;
box-sizing: border-box;
}

.div2 {
width: 300px;
height: 100px;
padding: 50px;
border: 1px solid red;
box-sizing: border-box;
}

Try it out . . .

box-sizing: border-box; It works better, and that's exactly what many developers need.

The following code allows all elements to present size in a more intuitive way. M any browsers already box-sizing: border-box; (But not all - that's why the input and text elements are set width: 100%;) t he width is different).

Using box-sizing for all elements is more recommended:

Instance

* {
box-sizing: border-box;
}

Try it out . . .