元素垂直居中

137 阅读1分钟
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .box{
            width: 300px;
            height: 300px;
            background-color: gray;
            position:relative;  //针对position定位时存在
        }
        .box1{
            display: table-cell;
            vertical-align: middle;
            text-align: center;
        }
        .box2{
            display: flex;
            justify-content:center;
            align-items:Center;
        }
        .box3 div{
            width: 50%;
            height: 50%;
            background: #000;
            overflow: auto;
            margin: auto;
            position: absolute;
            top: 0; left: 0; bottom: 0; right: 0;
        }
        .box4 div{
            position: absolute;
            top:50%;
            left:50%;
            width:100%;
            transform:translate(-50%,-50%);
            text-align: center;
        }
    </style>
</head>
<body>
<div class="box box1">
    <!--<span>垂直居中</span>-->
    <div>垂直居中</div>
</div>
<div class="box box2">
    <!--<span>垂直居中</span>-->
    <div>垂直居中</div>
</div>
<div class="box box3">
    <!--<span>垂直居中</span>-->
    <div>垂直居中</div>
</div>
<div class="box box4">
    <!--<span>垂直居中</span>-->
    <div>垂直居中</div>
</div>
</body>
</html>