理解border-box
source link: https://foofish.net/border-box.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
box-sizing
可以控制盒模型的行为,默认值是content-box
, 另一个属性值是 border-box
。在理解 border-box 的作用前,先来看一个例子。
<div class="container"> <div class="left">left</div> <div class="right">right</div> </div>
容器盒子里面有两个子元素,我们希望两个元素的左右布局,显示在一行。
我们给他配上样式
.container { background-color: #aaa; width: 600px; margin: 10px auto; border: 1px solid #000; } .left { background-color: #fff; width: 400px; float: left; height:200px; border: 1px solid #ccc; } .right{ width:200px; float:left; background-color: #fff; border: 1px solid #ccc; height:200px; } .container::after{ content: ""; display: block; clear:both; }
container容器的宽度是600px,子元素 left 的宽度400px,right 的宽度是200px。使用浮动的方式让两个div显示在一行,但结果是右边的div换行了。
原因就是div的box-sizing
默认属性值是 content-box
, 它的特点是,你设置的width
是内容的宽度,如果加上外边距、内边距、和边框的宽度,元素的实际宽度是 width+margin+padding+border 。
所以这里右边的子元素实际宽度是202,因为边框左右各有1px。如果要使得这两个元素放在一行,必须将其中一个元素的 width 减少2px。
除此之外,第二种方式就是将box-sizing
的值改成border-box
, 该属性的行为表现为:当你设置width:200px, 这个元素的实际宽度就是200px,这个值是内容的宽度+内外边距以及边框之和, 因此,这时候再设置边距只会减少内容的宽度,因为总宽度已经是固定值了。
设置为boder-box后, left 400, right200 加起来宽度正好是600。 所以他们就能显示在一行了。这也是通用做法
同时为了将该属性设置为通用行为,让所有元素的行为表现一致,可以设置全局样式
*; ::before, ::after{ box-sizing: border-box; }
有问题可以扫描二维码和我交流
关注公众号「Python之禅」,回复「1024」免费获取Python资源
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK