CSS的基础学习5 -盒模型

盒模型其实就是内边距padding、边框border、外边距margin,他们三者就构成了一个“盒子”,盒子里装着你想放的元素,其中边框就是内边距和外边距的分界线。盒模型是很基础的东西,但发现盒子模型不仅仅是margin,padding和border,其实还有其他的知识。

<html>
<head>
<style>
#box1
{
width: 200px;
border:1px solid #000;
background-color:yellow;
}
#box2{
  margin: 10px;
 padding: 5px;
border:10px solid #fff;
background-color:red;
}
</style>
</head>
<body>
<div id="box1"><div id="box2">外边距距离父级元素10px;内边距距离内部元素5px;边框厚度10px;</div>
</div>
</body>
</html>





外边距距离父级元素10px;内边距距离内部元素5px;边框厚度10px;



当我们为这个盒子设置宽度的时候,width的值是盒子内容的宽度,而不是整个盒子的大小,整个盒子的大小是margin+padding+border+width,其中有一项改变了,整个盒子的大小就改变了。当我们设置box-sizing:border-box的时,盒子的大小就不包括margin了,而是boder的外边界的大小。

<html>
<head>
<style>
#box5
{
width: 200px;
border:1px solid #000;
background-color:yellow;
}
#box6{
width:100px;
  margin: 10px;
 padding: 5px;
border:10px solid #fff;
background-color:red;
box-sizing:border-box;
}
</style>
</head>
<body>
<div id="box3"><div id="box4">文本内容100px</div>
</div>
</body>
</html>





文本内容100px








不包含margin,文本加padding加边框大小总共为100px



建议以后写css时候,把box-sizing:border-box;设置好

*{
padding:0;
margin:0;
box-sizing:border-box;
}

margin–纵向重叠

两个段落之间纵向的距离按常理来说应该是 10 + 10 = 20px,但是实际还是为10px

<html>
<head>
<style>
.prom{
margin:10px;
}
</style>
</head>
<body>
<div class="prom">123</div>
<div class="prom">123</div>
<div class="prom">123</div>
</div>
</body>
</html>
123
123
123

横向的话就不会,把div改为a标签后

123123123

经过测量123之间为20px

且纵向重叠大的会吃掉小的,纵向两元素相隔为当中的最大值

  • max-width:给元素设置最大宽度值
  • min-width:给元素设置最小宽度值

max-width 会覆盖width设置, 但 min-width设置会覆盖 max-width.