一、垂直居中
1、利用margin
*{margin:0; padding:0; position:relative;}
.div1{width:400px; height:400px; background:#f00;margin:20px auto; overflow:hidden;}
.div2{width:200px; height:200px; margin:100px 0 0 100px; background:#0f0;}
2、绝对定位
*{margin:0; padding:0; position:relative;}
.div1{width:400px; height:400px; background:#f00; position:relative; margin:20px auto;}
.div2{width:200px; height:200px; background:#0f0; position:absolute; left:100px; top:100px;}
3、绝对定位+margin外补丁
*{margin:0; padding:0; }
.div1{width:400px; height:400px; background:#f00; position:relative; margin:20px auto;}
.div2{width:200px; height:200px; background:#0f0; position:absolute; left:50%; top:50%;
margin:-100px 0 0 -100px;}
margin取负值,负值大小为层自身高度宽度各/2,如果加padding,border值等,为了不改变盒子需要设置box-sizing:border-box.
4、css3新增属性transform:translate(-50%,-50%)
*{margin:0; padding:0; }
.div1{width:400px; height:400px; background:#f00;position:relative; margin:10px auto; }
.div2{width:200px; height:200px; background:#0f0;position:absolute; left:50%; top:50%;
transform:translate(-50%,-50%);}
二、三个div
1、
*{margin:0; padding:0;}
body{margin:10px auto;}
.first{float:left;width:50%; height:300px; background:#f00;}
.sec{float:left;width:50%; height:300px; background:#0f0;}
.tir{float:left;width:100%; height:300px; background:#00f;}
2、
*{margin:0; padding:0;font-size:0;} /*font-size:0清除display:inline-block;元素换行符之间的间隙*/
.first{display:inline-block;width:50%; height:300px; background:#f00;}
.sec{display:inline-block;width:50%; height:300px; background:#0f0;}
.tir{width:100%; height:300px; background:#00f;}
3、
.first{width:50%; height:300px; background:#f00;}
.sec{width:50%; height:300px; background:#0f0; margin-left:50%; margin-top:-300px;}
.tir{width:100%; height:300px; background:#00f;}
4、
.first{width:50%; height:300px; background:#f00; position:absolute; left:0; top:0;}
.sec{width:50%; height:300px; background:#0f0; position:absolute; left:50%; top:0;}
.tir{width:100%; height:300px; background:#00f; position:absolute;left:0; top:300px;}