前端常见面试题(三)垂直居中的10种方式

1、flex布局(2种)

   .out {
            background: pink;
            width: 300px;
            height: 300px;
            display: flex;
            align-items: center;
        }

        .inner {
            background: blue;
            width: 100px;
        }
#box {
    width: 300px;
    height: 300px;
    background: #ddd;
    display: flex;
    flex-direction: column;
    justify-content: center;
}
#child {
    width: 300px;
    height: 100px;
    background: orange;
}

2、使用绝对定位和负外边距对块级元素进行垂直居中(必须提前 已知内部高度)

#out {
    width: 300px;
    height: 300px;
    background: #ddd;
    position: relative;
}
#inner {
    width: 150px;
    height: 100px;
    background: orange;
    position: absolute;
    top: 50%;
    margin: -50px 0 0 0; 
}

3、使用绝对定位和transform

#box {
    width: 300px;
    height: 300px;
    background: #ddd;
    position: relative;
}
#child {
    background: orange;
    position: absolute;
    top: 50%;
    transform: translate(0, -50%);
}

4、绝对定位结合margin: auto

#box {
    width: 300px;
    height: 300px;
    background: #ddd;
    position: relative;
}
#child {
    width: 200px;
    height: 100px;
    background: orange;
    position: absolute;
    top: 0;
    bottom: 0;
    margin: auto;
    line-height: 100px;
}

5、使用padding实现子元素的垂直居中(移动端ios系统input框经常用到)

#box {
    width: 300px;
    background: #ddd;
    padding: 100px 0;
}
#child {
    width: 200px;
    height: 100px;
    background: orange;
}

6、使用 CSS Grid,设置 .one .three 两个辅助元素即可, 只是 Grid 布局现在浏览器支持度还比较低  (2种)

使用 CSS Grid 设置水平居中

 法二:place-item:center;

7、使用 line-height 和 vertical-align 对图片进行垂直居中

vertical-align ,深入研究请参考张鑫旭 我对CSS vertical-align的一些理解与认识

本例具体的实现原理请参考张鑫旭 CSS深入理解vertical-align和line-height的基友关系

  

回顾:inline box模型,inline/inline-block/block属性。

8、使用 display: table; 和 vertical-align: middle; 对容器里的文字进行垂直居中

9、使用 line-height 对单行文本进行垂直居中

10、用基准线

原文地址:https://www.cnblogs.com/catherLee/p/13223883.html