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

CSS布局div之水平居中与垂直居中

2017-06-02 10:06 519 查看
水平居中

一个方法就可以:给div设置一个宽度,然后添加 margin:0 auto 属性。

任意的position属性都可以。(fixed absolute relative static)

div{
width:200px;
margin:0 auto;
}


水平垂直都居中

方法一:通过绝对定位实现

div{
position:absolute;
width:300px;
height:300px;
margin:auto;
top:0;
left:0;
bottom:0;
right:0;
background-color:purple;
}


方法二:设置层的外边距把div的中心点移到包含块的原点位置,再通过相对定位或者绝对定位向下向右移动50%;

要保证包含块有高度。

当position设置为relative时,若要使div在浏览器窗口垂直水平居中,需要将body以及html的height都设置为100%。

div{
position:relative; /*或者absolute*/
width:600px;
height:400px;
margin:-300px 0 0 -200px;
top:50%;
left:50%;
background-color:purple;
}


提示:

使用百分比单位时:

乘以包含块的高度 top, bottom, height, max-height, min-height。

乘以包含块的宽度 margin, padding, left, right, text-indent, width, max-width, min-width 。

方法三:容器高度不定,采用“transform”属性

div{
position:relative; /*或者absolute*/
width:600px;
top:50%;
left:50%;
transform:translate(-50%,-50%);
background-color:purple;
}


注意:transform属性需要考虑浏览器兼容问题,加上不同内核前缀。

方法四:利用flex布局

.container{
display:flex;
display:-webkit-flex;  /*浏览器兼容*/
align-items:center;  /*垂直居中*/
justify-content:center;  /*水平居中*/
}
.container div{
width:100px;
height:200px;
background-color:purple;
}


参考:

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