浮层水平垂直居中方法
(一)利用绝对定位与transform
<div class="parent">
<div class="children"></div>
</div>
将父元素定位,子元素如下
.children{
position: absolute;
top: 50%;
left: 50%;
-webkit-transform:translate(-50%,-50%);
background: black;
}
(二)利用flexbox
.parent{
justify-content:center;
align-items:center;
display: -webkit-flex;
}
(三)当子元素的宽高固定,父元素内含有除居中元素外其它元素(空标签也行)或者父元素的高度不为0时
将父元素定位,子元素绝对定位,利用margin负值为子元素宽高的一半来实现。
代码如下:
<div class="parent">
<div class="children"></div>
<span></span>
</div>
.parent{
position: relative;
background: red;
}
.children{
width: 200px;
height: 200px;
margin: -100px 0 0 -100px;
background: black;
position: absolute;
top: 50%;
left:50%;
}
(四)利用table
(五)display:table-cell
<div class="parent">
<div class="child">哈哈</div>
</div>
.parent{
width: 400px;
height: 100px;
background: black;
display: table-cell;
vertical-align: middle;
text-align: center;
}
.child{
background: red;
display: inline-block;
}
(六)利用定位与margin:auto
<div class="child">哈哈</div>
</div>
height: 400px;
background: red;
position: relative;
}
.children{
width: 200px;
height: 200px;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
background: black;
}