A Beginners Guide to CSS box-sizing property

The CSS box-sizing property lets you take control over the HTML elements width. Generally padding and border width of an HTML element adds themselves up to the elements width and makes it to stretch over. But if you don't want the HTML element to be stretched irrespective of padding and border width, then use the CSS box-sizing: border-box; property.

CSS box-sizing property

Recommended Read: CSS Margin Property

Here is an example in which there are two <div> blocks of width: 400px, where the first one is without padding and border and the second one with padding and border.

HTML Markup
<div id="div1">
I'm a <div> block without padding and border.
</div>

<div id="div2">
I'm a <div> block with padding and border.
</div>
CSS Code
#div1 { //without padding & border
     margin: 10px 0;
     width: 400px;
     background: #eee;
}

#div2 { //with padding & border
     margin: 10px 0;
     width: 400px;
     padding: 20px;
     background: #eee;
     border: 10px solid #777;
}
I'm a <div> block without padding and border.
I'm a <div> block with padding and border.

You can see the second <div> block is extended than the first one. This is because the left and right padding of total 40px and left and right border width of total 20px is added up to the width of 400px making the element width as 460px.

Recommended Read: CSS Border Property to set Color, Width and Style

Now we'll see what happens when we add box-sizing to #div2.

HTML Markup
<div id="div1">
I'm a <div> block without padding and border.
</div>

<div id="div2">
I'm a <div> block with padding and border.
</div>
CSS Code
#div1 { //without padding & border
     margin: 10px 0;
     width: 400px;
     background: #eee;
}

#div2 { //with padding & border
     margin: 10px 0;
     width: 400px;
     padding: 20px;
     background: #eee;
     border: 10px solid #777;
     box-sizing: border-box;
     -moz-box-sizing: border-box;
     -webkit-box-sizing: border-box;
}
I'm a <div> block without padding and border.
I'm a <div> block with padding and border.

See both the blocks takes up equal width now. Using the CSS box-sizing property made the padding and border width of the HTML element confined within its specified width and restricted it from stretching.

No comments:

Post a Comment