垂直水平居中布局的几种方法

第一种:绝对定位 + margin负值

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>垂直水平居中</title>
    <style>
        .parent{
            width: 400px;
            height: 400px;
            margin: 100px auto auto 600px;
            border: 1px solid #ccc;
            position: relative;
        }
        .box{
            width: 200px;
            height: 200px;
            background-color: pink;
            position: absolute;
            top: 50%;
            left: 50%;
            margin-left: -100px;
            margin-top: -100px;
        }
    </style>
</head>

<body>
    <div class="parent">
        <div class="box"></div>
    </div>
</body>

</html>

效果:

 注意,如果是相对于浏览器窗口,则不需要position:relative;

第二种:使用css3属性transform

.box{
    width: 200px;
    height: 200px;
    background-color: pink;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);//往上(x轴),左(y轴)移动自身长宽的 50%,使其居于中心位置
}

第三种:使用flex布局

第四种: 使用table-cell

看一下效果:

 

注意的是,我设置了margin,但是父元素却并没有体现这一点,这是因为设置了table-cell的元素对margin值无反应,但是它可以响应padding的设置,而且使用这一属性时,不要与float属性和position:absolute; 一起使用。

猜你喜欢

转载自blog.csdn.net/qq_41588568/article/details/108795059