如何让一个div水平垂直居中

1,231 阅读2分钟

(1)定位(必须知道父、子元素宽高的情况)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .parent {
            width: 500px;
            height: 500px;
            border: 2px solid #333;
            position: relative;
        }
        .child {
            width: 100px;
            height: 100px;
            position: absolute;
            top: 50%;
            left: 50%;
            margin-top: -50px;
            margin-left: -50px;
            background-color: lightgreen;
        }
    </style>
</head>
<body>
<div class="parent">
    <div class="child">
    </div>
</div>
</body>

(2)margin: auto(必须知道父、子元素宽高的情况)

子元素若不设置宽高,会占满父元素

.parent {
    width: 500px;
    height: 500px;
    border: 2px solid #333;
    position: relative;
}
.child {
    width: 100px;
    height: 100px; 
   position: absolute;
    margin:auto;
    top:0;
    left:0;
    right:0;
    bottom:0;
    background-color: lightgreen;
}

(3)display:table-cell(可以不知道子元素宽高,父元素的宽高必须明确)

.parent {
    width: 500px;
    height: 500px;
    border: 2px solid #333;
    display:table-cell;
    vertical-align:middle;
    text-align:center;
}
.child {
    width: 100px;
    height: 100px;
    display:inline-block;
    background-color: lightgreen;
}

(4)display:flex设置垂直水平都居中(可以不知道子元素宽高,且父元素的宽高可以为百分比)

.parent {
    width: 500px;
    height: 500px;
    border: 2px solid #333;
    display:flex;
    justify-content:center;
    align-items:center;
}
.child {
    width: 100px;
    height: 100px;
    background-color: lightgreen;
}

(5)计算父盒子与子盒子的空间距离(这跟方法一是一个道理);(必须知道子元素宽高)

计算方法:父盒子高度或者宽度的一半减去子盒子高度或者宽的的一半。

.parent {
    width: 500px;
    height: 500px;
    border: 2px solid #333;
}
.child {
    width: 100px;
    height: 100px; 
    margin-top:200px;
    margin-left:200px;
    background-color: lightgreen;
}

(6)定位加css3的平移(可以不知道子元素宽高,并且父元素宽高可以为百分比)

计算方法:子元素的左顶点,移动到父元素的中心处(top: 50%;left:50%;) 

再将子元素的中心点移动到父元素的中心处(transform: translate(-50%,-50%))

translate(-50%, -50%)作用是,往上(X轴),左(Y轴)移动自身长度的50%,以使其居于中心位置。

.parent {
    width: 500px;
    height: 500px;
    border: 2px solid #333;
    position: relative;
}
.child {
    width: 100px;
    height: 100px;
    position: absolute;
    top:50%;
    left:50%;
    transform:translate(-50%,-50%);
    background-color: lightgreen;
}

(7)通过计算得出,(父元素宽/高-子元素宽/高)/2 = left/top的值(必须知道子元素宽高))

.parent {
    width: 500px; 
   height: 500px;
    border: 2px solid #333;
    position: relative;
}
.child {
    width: 100px; 
   height: 100px;
    position: absolute;
    top:calc(200px);
    left:calc(200px);
    background-color: lightgreen;
}

效果图

以上是个人收集总结的方法,有不对的地方欢迎帮忙纠正