如何让子元素在父元素中水平垂直居中七种方法

html:

	<div class="container">
        <div class="box">green</div>
    </div>

第一种:定位+margin:auto

.container {
        position: relative;
        width: 300px;
        height: 300px;
        background: yellow;
    }
    .box {
        position: absolute;
        left: 0;
        top: 0;
        right: 0;
        bottom: 0;
        margin: auto;
        width: 100px;
        height: 100px;
        background: red;
    }

注意:兼容性较好,缺点:不支持IE7以下的浏览器
第二种:定位+margin-left+margin-top

.container {
        position: relative;
        width: 300px;
        height: 300px;
        background: yellow;
    }
    .box {
        position: absolute;
        left: 50%;
        top: 50%;
        margin-left: -50px;
        margin-top: -50px;
        width: 100px;
        height: 100px;
        background: red;
    }

注意:兼容性好;缺点:必须知道元素的宽高
第三种:定位+transfrom

.container {
        position: relative;
        width: 300px;
        height: 300px;
        background: yellow;
    }
    .box {
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%,-50%);
        width: 100px;
        height: 100px;
        background: red;
    }

注意:这是css3里的样式;缺点:兼容性不好,只支持IE9+的浏览器
第四种:弹性盒子

.container {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 300px;
        height: 300px;
        background: yellow;
    }
    .box {
        width: 100px;
        height: 100px;
        background: red;
    }

移动端首选
第五种:flex+margin: auto

.container {
        display: flex;
        width: 300px;
        height: 300px;
        background: yellow;
    }
    .box {
        margin: auto;
        width: 100px;
        height: 100px;
        background: red;
    }

移动端首选
第六种:形成table-cell,子元素设置display:inline-block

.container {
        display: table-cell;
        vertical-align: middle;
        text-align: center;
        width: 300px;
        height: 300px;
        background: yellow;
    }
    .box {
        display: inline-block;
        width: 100px;
        height: 100px;
        background: red;
    }

注意:兼容性:由于display:table-cell的原因,IE6\7不兼容
第七种:line-height+display:inline

.container {
        width: 300px;
        height: 300px;
        line-height: 300px;
        text-align: center;
        background: yellow;
    }
    .box {
        display: inline;
        background: red;
    }

职场小白south Joe,望各位大神批评指正,祝大家学习愉快!

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值