【经典面试题】不固定宽高的div水平垂直居中的3种方法

目录

一. 固定宽高div进行水平垂直居中

二.不固定宽高的div进行水平垂直居中

1、定位的方法

2、使用display:table-cell方法 

3、利用弹性布局 


一. 固定宽高div进行水平垂直居中

        .son {
            position: absolute;
            background: green;
            margin:auto;
            left: 0;
            top: 0;
            bottom: 0;
            right: 0;
        }

二.不固定宽高的div进行水平垂直居中

1、定位的方法

<body>
    <div>
        我是没有宽高的div
    </div>
</body>
<style>
div{
    /* 1 设置定位 */
    position: absolute;
    /* 2 x,y轴走网页的一半 */
    left: 50%;
    top: 50%;
    /* 3 往回走自身x,y的一半 */
    transform: translate(-50%,-50%)
}
</style>

2、使用display:table-cell方法 

<body>
    <div class="father">
        <div class="son">
            我没有宽高
        </div>
    </div>
</body>
<style>
.father {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
    width: 100px;
    heigth: 100px;
}
.son {
    vertical-align: middle;
    display: inline-block;
}
</style>

3、利用弹性布局 

<body>
   <div class="father">
       <div class="son">
           我没有宽高
       </div>
   </div>
</body>
<style>
.father{
    /* 1. 父盒子设置宽高*/
    width: 500px;
    height: 500px;
    /* 2. 添加flex属性 */
    display: flex;
    /* 3. 设置水平垂直居中 */
    justify-content: center;
    align-items: center;
}
</style>

猜你喜欢

转载自blog.csdn.net/m0_64346035/article/details/124851846