Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a border increase the element's width?

Tags:

html

css

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>
like image 585
Kaveh Avatar asked Oct 21 '25 18:10

Kaveh


2 Answers

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:

  1. content-box (default)
  2. border-box

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.

like image 99
kukkuz Avatar answered Oct 23 '25 07:10

kukkuz


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.

like image 30
Kewin Dousse Avatar answered Oct 23 '25 06:10

Kewin Dousse