Add border to div increase div width?

北慕城南 提交于 2019-11-27 05:38:50

As the border is around all the div, it is present both to its left and its right : You have to count its width it twice. So the final width will be 300 + 2*2 = 304px.

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;
  background-color:#A8F9C0;
  float:left;
  border:2px solid black;
  box-sizing: border-box;
}
<div class="test">
</div>

This will ensure the width stays the same and inlcudes the box border.

If you want the border to be on all 4 sides without increasing the width of the element, you can use outline instead:

.test{
    width:300px;
    height:auto;
    background-color:#A8F9C0;
    float:left;
    outline:2px solid black;
}
<div class="test">Test</div>

You could also use an inset box-shadow:

 .test{
    width:300px;
    height:auto;
    background-color:#A8F9C0;
    float:left;
    box-shadow:0 0 0 2px black inset;
}
<div class="test">Test</div>

The right and clean answer is box-sizing: border-box; Add it to your class test and your problem is gone.

Does 2px border cause that the the width of div be 302px

No it does not. When you set the width of an element you are setting the content area of an element.

However there what you are referring to is the outer width i.e. width + padding + border

To understand the difference look at how the box models work here https://developer.mozilla.org/en-US/docs/Web/CSS/width

And these links.

width : http://api.jquery.com/width/

inner width : http://api.jquery.com/innerwidth/

outer width : http://api.jquery.com/outerwidth/

Cheers and happy coding!

in CSS 2 you had to wrap the div inside another (Please note that you should not set width:100% for inner element and let it expand automatically):

var width=$("#test").width();
$("#result").html('Javascript says: The inner Width of element is '+width);
#wrapper{
  width:300px;
}
#test{
  border:2px solid #000000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="wrapper">
   <div id="test">&nbsp;</div>
</div>

<br>
<div id="result"></div>

in CSS 3 use box-sizing:

#test{
  width:300px;
  border:2px solid #000000;
  box-sizing:boder-box;
    }
<div id="test">&nbsp;</div>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!