1:设置元素绝对定位,通过margin属性,移动自身宽高的一半

2:设置元素绝对定位,设置margin:auto

3:设置弹性布局,通过align-items: center;justify-content: center;实现

4:设置元素绝对定位,通过transform属性,移动自身宽高的一半

代码:

<!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>Document</title>
    <style>
        html,body{width:100%;height:100%}
        /* 元素水平及垂直实现方式1 */
        #d1{
            position: relative;
            width:100%;
            height:100%;
            background-color:#f00;
        }
        .children{
            position:absolute;
            width:100px;
            height:100px;
            left:50%;
            top:50%;
            margin-left:-50px;
            margin-top:-50px;
            background-color:#fff;
        }
        /* 元素水平及垂直实现方式2 */
        #d1{
            position: relative;
            width:100%;
            height:100%;
            background-color:#f00;
        }
        .children{
            position:absolute;
            width:100px;
            height:100px;
            left:0;
            top:0;
            right:0;
            bottom:0;
            margin:auto;
            background-color:#fff;
        }
        /* 元素水平及垂直实现方式3 */
        #d1{
            width:100%;
            height:100%;
            background-color:#f00;
            display:flex;
            align-items: center;    /*垂直居中*/
            justify-content: center;    /*水平居中*/
        }
        .children{
            display: inline-block;
            width:100px;
            height:100px;
            background-color:#fff;
        }
        /* 元素水平及垂直实现方式4 */
        #d1{
            position: relative;
            width:100%;
            height:100%;
            background-color:#f00;
        }
        .children{
            position:absolute;
            width:100px;
            height:100px;
            background-color:#fff;
            left:50%;
            top:50%;
            transform: translate(-50% -50%);
        }
    </style>
</head>
<body>
    <div id="d1">
        <div class="children"></div>
    </div>
</body>
</html>

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐