css实现垂直居中(面试的时候面试官经常会问的)

1.absolute + margin auto

<style>
    .wrap {
        position: relative;
        width: 200px;
        height: 200px;
        border: 1px solid blueviolet;
    }
    .children {
        margin:auto;
        bottom: 0;
        right: 0;
        left: 0;
        top: 0;
        position: absolute;
        width: 100px;
        height: 100px;
        background: beige;
    }
</style>
<body>
<div class="wrap">
    <div class="children">子元素</div>
</div>
</body>

2.absolute + 负margin

<style>
    .wrap {
        position: relative;
        width: 200px;
        height: 200px;
        border: 1px solid blueviolet;
    }
    .children {
        margin-left: -50px;
        margin-top: -50px;
        top: 50%;
        left: 50%;
        position: absolute;
        width: 100px;
        height: 100px;
        background: beige;
    }
</style>
<body>
<div class="wrap">
    <div class="children">子元素</div>
</div>
</body>

3.absolute + calc

<style>
    .wrap {
        position: relative;
        width: 200px;
        height: 200px;
        border: 1px solid blueviolet;
    }
    .children {
        top:calc(50% - 50px);
        left:calc(50% - 50px);
        position: absolute;
        width: 100px;
        height: 100px;
        background: beige;
    }
</style>
<body>
<div class="wrap">
    <div class="children">子元素</div>
</div>
</body>

4.absolute + transform

<style>
    .wrap {
        position: relative;
        width: 200px;
        height: 200px;
        border: 1px solid blueviolet;
    }
    .children {
        top:50%;
        left:50%;
        position: absolute;
        transform: translate(-50%,-50%);
        width: 100px;
        height: 100px;
        background: beige;
    }
</style>
<body>
<div class="wrap">
    <div class="children">子元素</div>
</div>
</body>

5.flex

<style>
    .wrap {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 200px;
        height: 200px;
        border: 1px solid blueviolet;
    }
    .children {
        width: 100px;
        height: 100px;
        background: beige;
    }
</style>
<body>
<div class="wrap">
    <div class="children">子元素</div>
</div>
</body>

6.css-table

<style>
    .wrap {
        display: table-cell;
        text-align: center;
        vertical-align: middle;
        width: 200px;
        height: 200px;
        border: 1px solid blueviolet;
    }
    .children {
        display: inline-block;
        width: 100px;
        height: 100px;
        background: beige;
    }
</style>
<body>
<div class="wrap">
    <div class="children">子元素</div>
</div>
</body>

总结:

这些是我经常使用的,如有新的方法,欢迎交流

对比优缺点:

1.pc端宽高固定建议使用:absolute + 负margin;

2.pc端无宽高:css-table;

3.无兼容性:flex;

4.移动端建议使用flex,真的超级好用

猜你喜欢

转载自blog.csdn.net/weixin_43204255/article/details/82702061