CSS未知宽高的元素,水平垂直居中

方法一:使用定位

思路:子元素绝对定位,距离顶部 50%,左边50%,然后使用css3 transform:translate(-50%; -50%)
优点:高大上,可以在webkit内核的浏览器中使用
缺点:不支持IE9以下不支持transform属性

<style>
.parent{
    position: relative;
    height:300px;
    width: 300px;
    background: #FD0C70;
}
.parent .child{
    position: absolute;
    top: 50%;
    left: 50%;
    color: #fff;
    transform: translate(-50%, -50%);
}
</style>
<body>
<div class="parent">
        <div class="child">hello world</div>
    </div>
</body>

方法二:使用弹性布局


思路:使用css3 flex布局
优点:简单 快捷
缺点:兼容不好

<style>
.parent{
    display: flex;
    justify-content: center;
    align-items: center;
    width: 300px;
    height:300px;
    background: #FD0C70;
}
.parent .child{
    color:#fff;
}
</style>
<body>div> <div class="parent">
        <div class="child">hello world</div>
    </div>
</body>

猜你喜欢

转载自blog.csdn.net/Web_J/article/details/84592827