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

水平居中
一个方法就可以:给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布局详解

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值