父元素、子元素宽高不定的情况下居中的几种方法

基本的HTML结构
<div class="parent">
    <div class="child">DEMO</div>
</div>

水平居中

一、inline-block、text-align:center

特点:适应性好,IE6、IE7不兼容inline-block。text-align:center会导致子元素的内容也居中。

<style>
    .parent{
        text-align: center;
    }
    .child{
        display: inline-block;/*宽度跟内容变化*/
    }
</style>

 二、table+margin

特点:只需要对子元素设置,IE6、IE7不支持table,

<style type="text/css">
    .child{
        display: table;/*宽度跟内容变化*/
 margin: 0 auto; } </style>

三、absolute+transform

特点:子元素不会影响其他元素,transform是CSS3内容,不兼容IE6、IE7、IE8。

<style type="text/css">
    .parent{
        position: relative;
    }
    .child{
        position: absolute;
        left: 50%;
        transform: translateX(-50%);/*向左移自身宽度一半*/
    }
</style>

四、flex+justify-content

特点:只对父容器设置,是CSS3内容,不兼容IE6、IE7、IE8。

<style type="text/css">
 .parent{
        display: flex;
        justify-content: center;/*设置了这个就用用设置子元素margin: 0 auto*/
 }
.child{ margin: 0 auto;/*如果不用justify-content: center,可以用这个*/ }

</style>

 垂直居中

一、table-cell+vertical-align

要兼容IE7及以下,要更换为table结构

.parent{
        display: table-cell;
        vertical-align: middle;
    }

二、absolute+transform

transform兼容性问题

.parent{
        position: relative;
    }
    .child{
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
    }

三、flex+align-items

flex、align-items兼容性问题

.parent{
        display: flex;
        align-items: center;
    }

水平垂直居中

一、

 

.parent{width:200px;height:300px;}
    
    .parent{
        text-align: center;
        display: table-cell;
        vertical-align: middle;
    }
    .child{
        display: inline-block;
    }

二、

 

.parent{width:200px;height:300px;}
    
    .parent{
        position: relative;
    }
    .child{
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%,-50%);
    }

三、

 

.parent{width:200px;height:300px;}
    
    .parent{
        display: flex;
        justify-content: center;
        align-items: center;
    }

 

转载于:https://www.cnblogs.com/webstong/p/5903670.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值