css盒子垂直水平居中

124 阅读1分钟

一、绝对定位方法:不确定当前div的宽度和高度,采用 transform: translate(-50%,-50%); 当前div的父级添加相对定位(position: relative;)

<!DOCTYPE html>
<html lang="en"> 
<head> 
<meta charset="UTF-8">
<title>水平垂直居中方式1</title> 
    <style> 
    /*使用绝对定位,不确定子div的宽高,父元素需要添加position:relative*/ 
    .father { background: red; position: relative; width: 500px; height: 500px; } 
    .son { background: green; position: absolute; left: 50%; top: 50%; transform: translate(-50%,-50%); } 
    </style> 
</head> 
<body> 
    <div class="father"> 
        <div class="son">hello simon</div> 
    </div> 
</body> 
</html>

二、绝对定位方法:确定了当前div的宽度,margin值为当前div宽度一半的负值

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>水平垂直居中方式2</title>
    <style>
        /*使用绝对定位,确定了子div的宽高,margin值为子div宽高的一半的负值*/
        .father {
            background: red;
            position: relative;
            width: 500px;
            height: 500px;
        }
        .son {
            width: 200px;
            height: 200px;
            background: green;
            position: absolute;
            left: 50%;
            top: 50%;
            margin-left: -100px;
            margin-top: -100px;
        }
    </style>
</head>
<body>
<div class="father">
    <div class="son">hello simon</div>
</div>
</body>
</html>

三、绝对定位方法:绝对定位下top left right bottom 都设置0 ,margin设置为auto

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>水平垂直居中方式3</title>
    <style>
     /*使用绝对定位,确定了子div的宽高,left、right、top、bottom都设置为0,margin设置为auto*/
        .father {
            background: red;
            position: relative;
            width: 500px;
            height: 500px;
        }
        .son {
            width: 200px;
            height: 200px;
            background: green;
            position: absolute;
            left: 0;
            top: 0;
            bottom: 0;
            right: 0;
            margin: auto;
        }
    </style>
</head>
<body>
<div class="father">
    <div class="son">hello simon</div>
</div>
</body>
</html>

四、flex布局方法:当前div的父级添加flex css样式

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>水平垂直居中方式4</title>
    <style>
        /*使用flex布局,为父div添加flex布局样式align-items和justify-content*/
        .father {
            background: red;
            position: relative;
            width: 500px;
           height: 500px;
              -webkit-display: flex;
            display: flex;
            -webkit-align-items: center;
            align-items: center;
            -webkit-justify-content: center;
            justify-content: center;
        }
        .son {
            width: 200px;
            height: 200px;
            background: green;
        }
    </style>
</head>
<body>
<div class="father">
    <div class="son">hello simon</div>
</div>
</body>
</html>