I have a div as below. Its specified width is 300px, and it has a border width of 2px.
Why does the 2px border cause the width of the div to be 304px? What if I want it to have a border but still be 300px wide?
.test {
width: 300px;
height: auto;
border: 2px solid black;
}
<div class="test">
</div>
What you have stumbled across is the foundation of the CSS box-model.
You can play with it using the box-sizing property which has two possible values:
content-box Default. The width and height properties (and min/max properties) includes only the content. Border, padding, or margin are not included
border-box The width and height properties (and min/max properties) includes content, padding and border, but not the margin
(source: W3Schools.com)
By default, the border will add on to your container width/height.
See what happens when you use border-box:
.test {
width: 300px;
height: auto;
border: 2px solid black;
box-sizing: border-box;
}
<div class="test">
</div>
This will ensure the width stays the same and includes the box border.
As the border is around all sides of the div, it is present both to its left and its right. You have to count the border's width twice. So the final width of the div will be 300 + 2*2 = 304px.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With