清除所有样式的内外边距
*{
margin: 0;
padding: 0;
}
单行文字垂直居中
让文字的行高等于容器的高度
div{
height:20px;
line-height:20px;
}
块级元素水平居中
必须指定宽度
左右外边距设置为auto
div{
width:200px;
margin:0 auto;
}
行内元素/行内块元素水平居中
把其看作文字,给其父元素添加属性text-align:center
<div class="container">
<span>这是一段文字</span> //行内元素
<img src = "xxx"> //行内块元素
</div>
···
<style>
.container{
text-align:center;
}
</style>
解决嵌套外边距合并(塌陷)
父子容器有相同的margin-xx时,二者的margin-xx会一起取较大值,造成父子容器紧贴的情况
注意:只有标准流才会有外边距塌陷问题,浮动盒子不会发生外边距塌陷
例:
<div class="father">
<div class="son">
这是一段文字
</div>
</div>
<styl>
.father{
margin-top:50px;
}
.son{
margin-top:100px;
}
</style>
/*此时父子容器的上边距都会被替换为100px*/
解决办法:
1.给父容器一个边框
.father{
margin-top:50px;
border: 1px solid transparent;
}
2.给父容器一个内边距
.father{
margin-top:50px;
padding:1px;
}
3.在父容器中添加overflow: hidden属性
============ 推荐 ============
因为上述两种方法都会改变父容器的原有样式,而这种不会
.father{
margin-top:50px;
overflow: hidden;
}
============================== 持续更新 ==============================