您的位置:首页 > Web前端 > CSS

css水平垂直居中的几种方式

2018-08-17 11:35 771 查看

html代码如下:

//html
<div class="parent">
<div class="child"></div>
</div>

一 、脱离文档流的居中

1、margin: auto居中

.parent{
width: 900px;
height: 400px;
background: red;
position: relative;
}
.child{
width: 50%;
height: 50%;
background: blue;
position: absolute;
margin: auto;
left: 0;
top: 0;
right: 0;
bottom: 0;
}

2、负margin居中

.parent{
width: 900px;
height: 400px;
background: red;
position: relative;
}
.child{
width: 400px;
height: 300px;
background: blue;
position: absolute;
left: 50%;
top: 50%;
margin-left: -200px;
margin-top: -150px;
}

二、未脱离文档流的水平垂直居中

1、display:table-cell居中

.parent{
width: 900px;
height: 400px;
background: red;
display: table-cell;
vertical-align: middle;
}
.child{
width: 50%;
height: 50%;
background: blue;
margin:  0 auto;
}

2、flex居中

.parent{
width: 900px;
height: 400px;
background: red;
display: flex;
display: -webkit-flex;
align-items: center; //控制垂直方向居中
-webkit-align-items: center;
justify-content: center; //控制水平方向居中
-webkit-justify-content: center;
}
.child{
width: 50%;
height: 50%;
background: blue;
}

ok~ 本篇圆满完结~

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: