定宽高的div元素垂直水平居中

关键点在于:采用绝对定位,使元素盒子左顶点位于垂直居中位置,再设置margin-left与margin-top值,使元素中心位于垂直居中位置。

贴上代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>固定高度div写法</title>
     <style>
         body {
            background: #abcdef;
         }
        .son {
            width: 200px;
            height: 100px;
            position: absolute;
            top: 50%;
            left: 50%;
            margin-left: -100px;
            margin-top: -50px;
            border: 1px solid red;
        }
     </style>
</head>
<body>
        <div class="son"></div>
</body>

</html>
View Code

效果图:

猜你喜欢

转载自www.cnblogs.com/caoxueying2018/p/10938091.html