前端培训丁鹿学堂:面试高频之 css垂直居中

69 阅读1分钟

如果面试要问css,这个问题的频率是很高的。这次让我们总结下来,一步到位。

垂直居中的5种方式

1.定位+ margin:这种适合子元素的宽高都确定的情况

    <style>
        .fa{
            width:500px;
            height: 500px;
            position: relative;
            background: yellowgreen;
        }
        .son{
            width:100px;
            height: 100px;
            background: red;
            position: absolute;
            left:50%;
            top:50%;
            margin-top:-50px;
            margin-left:-50px;

        }
    </style>

2.定位+ margin:auto。 这种适合父元素和子元素的高度确定的情况下

    <style>
        .fa{
            width:500px;
            height: 500px;
            position: relative;
            background: yellowgreen;
        }
        .son{
            width:100px;
            height: 100px;
            background: red;
            position: absolute;
            left:0px;
            top:0px;
            right: 0px;
            bottom: 0px;
            margin: auto;

        }
    </style>

3.定位+transform: 适合不确定子元素宽度的情况

    <style>
        .fa{
            width:500px;
            height: 500px;
            position: relative;
            background: yellowgreen;
        }
        .son{
            width:100px;
            height: 100px;
            background: red;
            position: absolute;
            left:50%;
            top:50%;
            transform: translate(-50%,-50%);

        }
    </style>

4.flex布局,简单高效,又显得你懂新技术(代码图四)

    <style>
        .fa{
            width:500px;
            height: 500px;
            background: red;
            display: flex;
            align-items: center;
            justify-content: center;

        }
        .son{
            width:100px;
            height: 100px;
            background: yellowgreen;
        }
    </style>

5.grid布局,和flex很像,记住了flex,就能记住grid(代码图五)

    <style>
        .fa{
            width:500px;
            height: 500px;
            background: red;
            display: grid;
            align-items: center;
            justify-content: center;

        }
        .son{
            width:100px;
            height: 100px;
            background: yellowgreen;
        }
    </style>

说前三种,基本就过关了,加上后两种,就能留下好印象,显得你比较热爱前端,知道新一点的技术,而不是一直在用定位这些。

其实还有很多,但是基本都大差不差,多了还容易记混。所以总结5种是恰到好处的!

而且,实际中应用的基本是第3,4种,这两个不仅要记熟,还要用熟。