一、什么是外边距margin
盒子模型由四部分组成,即内容(content),内边距(padding),边框(border),外边距(margin)。其中margin属性是用与设置外边距,即盒子与盒子之间的距离。
使用margin可以对各边距分别使用
/*下外边距*/
.A{
margin-bottom: 20px;
}
/*上外边距*/
.A{
margin-top: 20px;
}
/*右外边距*/
.A{
margin-right: 20px;
}
/*左外边距*/
.A{
margin-left: 20px;
}
也可以一起使用margin
/*指定一个值,作用于所有边距*/
.A{
margin: 20px;
}
/*指定两个值,第一个值作用于上下边距,第二个值作用于左右边距*/
.A{
margin: 20px 20px;
}
/*指定三个值,第一个值作用于上边距,第二个值作用于左右边距,第三个值作用于下边距*/
.A{
margin: 20px 20px 20px;
}
/*指定四个值,分别作用于上边距,右边距,下边距,左边距*/
.A{
margin: 20px 20px 20px 20px;
}
二、块级元素的对齐
使用外边距可以实现块级盒子居中对齐,只需满足两个条件:
- 盒子必须指定宽度。
- 盒子的左右边距设置为auto。
.header{
width: 500px;
background-color: palegreen;
margin: 0 auto;
}
三、行内元素,行内块元素水平居中
行内元素,行内块元素水平居中使用text-align: center即可。
.header{
width: 500px;
height: 500px;
background-color: palegreen;
margin: 0 auto;
text-align: center;
}
<div class="header">
<span>行内元素</span>
</div>
四、嵌套块元素外边距合并导致的塌陷
什么是嵌套块元素塌陷:对于两个嵌套关系(父子关系)的块元素,父元素有上边距子元素也有上边距,此时父元素会塌陷较大的外边距值。
<style>
.father{
width: 500px;
height: 500px;
background-color: palegreen;
margin-top: 10px;
}
.son{
width: 100px;
height: 100px;
background-color: purple;
margin-top: 20px;
}
</style>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
解决办法:
- 给父元素定义边框
<style>
.father{
width: 500px;
height: 500px;
background-color: palegreen;
margin-top: 10px;
border: 1px solid transparent;
}
.son{
width: 100px;
height: 100px;
background-color: purple;
margin-top: 20px;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
2. 给父元素一个内边距
<style>
.father{
width: 500px;
height: 500px;
background-color: palegreen;
margin-top: 10px;
padding: 1px;
}
.son{
width: 100px;
height: 100px;
background-color: purple;
margin-top: 20px;
}
</style>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
3.为父元素添加over-flow: hidden
<style>
.father{
width: 500px;
height: 500px;
background-color: palegreen;
margin-top: 10px;
overflow: hidden;
}
.son{
width: 100px;
height: 100px;
background-color: purple;
margin-top: 20px;
}
</style>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>