前端面试 CSS— 让元素垂直居中的方法有哪些?

Posted aiguangyuan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了前端面试 CSS— 让元素垂直居中的方法有哪些?相关的知识,希望对你有一定的参考价值。

 如何让元素垂直居中?这是一道很常见的面试题,大致有以下5种:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>让元素垂直居中的方法有哪些</title>
    <style>
        *{
            margin:0;
            padding:0;
        }
        body>div{
            /* 加个边框方便看 */
            border-bottom:1px solid #000;
        }
    </style>
</head>
<body>

    <div style="height:100px;line-height:100px;">
        纯文字类的水平居中
    </div>

    <div style="position:relative;height:100px;">
        <!-- 如果不加定位,子元素的上边距会影响父元素 ,同时margin-top也是需要计算的-->
        <div style="position:absolute;height:50px;margin-top:25px;line-height:50px;">
            用绝对定位加上外边距实现垂直居中
        </div>
    </div>

    <div style="position:relative;height:100px;">
        <!-- 如果想水平也居中,可以加上:left:50%;transform改成translate(-50%,-50%); -->
        <div style="position:absolute;top:50%;transform:translateY(-50%);">
            用绝对定位加平移实现垂直居中
        </div>
    </div>

    <div style="display:flex;height:100px;">
        <!-- 这种方法不仅实现了垂直居中,还实现了水平居中 -->
        <div style="margin:auto">
            用弹性布局实现垂直居中
        </div>
    </div>


    <div style="display:table;height:100px;">
        <div style="vertical-align:middle;display:table-cell;">
            用表格布局实现垂直居中的
        </div>
    </div>


</body>
</html>

以上是关于前端面试 CSS— 让元素垂直居中的方法有哪些?的主要内容,如果未能解决你的问题,请参考以下文章

华图教育_南京_前端实习面试

用CSS 实现元素垂直居中,都有哪些好的方案

Web前端面试题-1

前端面试CSS系列——DIV垂直水平居中

前端CSS面试题2023前端最新版css模块,高频15问

web前端—css面试题