常见面试题—CSS实现垂直水平居中

前言

面试中常常被问到,如何使用css来实现一个元素的垂直水平方向上居中,特别是笔试题的时候,这道题目的出现频率还是比较高的,当然,在我们的生活中,也常常会有垂直水平居中的需求。

CSS实现垂直水平居中的三种方案

1.容器内元素display:inline/inline-block

这种情况就比较容易了,直接设置容器的text-align就可以实现内容元素的水平居中,设置垂直居中的话要设置容器的高度,然后设置容易的line-height===height就可以,如下:

     <div class="container">
        <span>this is text</span>
     </div>
    .container{
        text-align: center;
        height: 50px;
        background: green;
        line-height: 50px;
    }

2.容器内元素display:block,且元素宽高已知

这种情况下我们使用position这个属性结合设置偏移来实现。首先设置容器的position:relative,设置元素position为absolute,然后设置元素(.inner-box)的偏移top,left,margin-top,margin-left,其中,top,left设置为50%,而margin-top/margin-left的偏移量均为本身元素高/宽的一半,为负值。

代码如下:


    <div class="container">
        <div class="inner-box"></div>
    </div>
    .container {
        height: 200px;
        width: 200px;
        background: pink;
        position: relative;
    }

    .inner-box {
        position: absolute;
        top: 50%;
        left: 50%;
        margin-top: -50px;
        margin-left: -50px;
        height: 100px;
        width: 100px;
        background: green;
    }


3.容器内元素display:block,且元素宽高未知

这种方法与方法二类似,但是不同的是不能通过设置margin-top/left偏移来达到效果了,因为容器内元素的宽高是未知的。这次我们通过设置left/top/bottom/right:0,然后设置margin:auto。
代码如下:

    <div class="container">
        <div class="inner-box"></div>
    </div>
    .container {
            height: 200px;
            width: 200px;
            background: pink;
            position: relative;
        }

    .inner-box {
        position: absolute;
        height: 100px;
        width: 100px;
        top: 0;
        right: 0;
        left: 0;
        bottom: 0;
        margin: auto;
        background: green;
    }

后话

实现垂直水平居中的方式有多种,通过设置translate,或者使用flex布局也是可以的,但是以上写的几种方法是兼容性比较好的。如果有不足,欢迎这位大佬指出。

猜你喜欢

转载自blog.csdn.net/nongweiyilady/article/details/80654457
今日推荐