不管是新手还是老手,fed们都会遇到水平和垂直居中问题。是一个div居中,水平方向上谁都会,那就是margin: 0 auto
。但是垂直居中就需要点技巧了,不过代码也不复杂,下面是同时水平垂直居中的两种方法。
html 片段如下:
<div class="parent">
<div class="children"></div>
</div>
父元素的css如下:
.parent {
position: relative;
width: 300px;
height: 500px;
background-color: red;
}
方法1
.children {
width: 200px;
height: 200px;
margin: auto;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
background-color: green;
}
方法2
.children {
width: 200px;
height: 200px;
position: relative;
margin: 0 auto;
top: 50%;
transform: translateY(-50%);
background-color: green;
}
方法3
—————更新于2016/6/16,实用flex布局实现———————
.parent {
width: 300px;
height: 500px;
background-color: red;
/* flex布局 */
display: flex;
}
.children {
width: 200px;
height: 200px;
background-color: green;
/* 下面2行实现水平垂直居中 */
align-items: center;
justify-content: center;
}