CSS居中布局
既要水平方向居中,也要垂直方向居中,就是在页面中心
实现方法:
- table + margin 实现水平方向居中,table-cell + vertical-align实现垂直方向居中
- absolute + transform实现水平方向合和垂直方向居中
实现方法:
两种方法实现的效果,其实都一样
第一种方法
.parent {
width: 1000px;
height: 600px;
background-color: antiquewhite;
display: table-cell;
/*<td>*/
vertical-align: middle;
}
.son {
width: 200px;
height: 200px;
background-color: brown;
display: table;
/*display: block也可以实现同样视觉效果,更加语义化*/
/*<table>*/
margin: 0 auto;
}
body:
<!--定义一个父元素-->
<div class="parent">
<!--定义一个子元素-->
<div class="son">
</div>
</div>
优点:
浏览器兼容性好
第二种方法
.parent {
width: 1000px;
height: 600px;
background-color: antiquewhite;
position: relative;
}
.son {
width: 200px;
height: 200px;
background-color: brown;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
body同上