元素水平垂直居中的四种方式

css部分

<style>
    .father{
        width: 300px;
        height: 300px;
        margin: 100px auto;
        border: 1px solid red;

        position: relative;
    }

    .son{
        width: 100px;
        height: 100px;
        background-color: green;
        
        /* 1.margin实现元素居中
            特点:父元素或子元素宽高发生变化,都需要重新计算
         */
        /* margin-top: 100px;
        margin-left: 100px; */

        /* 2.先使用定位:子绝父相 ,再用margin-left跟margin-top走自己宽高的一半
            特点:子元素元素宽高发生变化,需要重新计算
        */
        /* position: absolute;
        left: 50%;
        top: 50%;
        margin-top: -50px; 
        margin-left: -50px;  */

        /* 3.使用transform:translate(x,y) 
            好处:元素宽高变化,都会自动居中(transform属性值的百分比都是相对于元素自身宽高 )
        */

        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%,-50%);
         /* 4.伸缩盒子居中 */
        display: flex;
        justify-content: center;
        align-items: center;
    }
</style>

html部分

<div class="father">
    <div class="son"></div>
</div>
发布了4 篇原创文章 · 获赞 0 · 访问量 114

猜你喜欢

转载自blog.csdn.net/Tangoneone/article/details/104004532