CSS实现水平垂直居中

47 阅读1分钟

1. 页面基础结构

(1)HTML结构

 <div class="father">
        <div class="son"></div>
 </div>

(2)CSS样式

 .father {
            width: 500px;
            height: 300px;
            background-color: skyblue;
            margin: 0 auto;
        }

        .son {
            width: 100px;
            height: 100px;
            background-color: pink;
        }

(2)初始图 image.png

2. absolute + margin auto

CSS样式

        .father {
            position: relative;
            width: 500px;
            height: 300px;
            background-color: skyblue;
            margin: 0 auto;
        }

        .son {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            width: 100px;
            height: 100px;
            background-color: pink;
            margin: auto;
        }

3. absolute + 负margin

(1)先让子元素相对于父元素左上角偏移50%

        .son {
            position: absolute;
            top: 50%;
            left: 50%;
        }

image.png (2)让子元素根据自身位置偏移自身宽高的一半

        .son {
            position: absolute;
            top: 50%;
            left: 50%;
            margin-left: -50px;
            margin-top: -50px;
            /* 省略部分代码 */
        }

image.png

4. absolute + transform

(1)CSS样式

.son {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            /* 省略部分代码 */
        }

5. flex

(1)CSS样式

设置flex布局使得子元素分别在主轴与侧轴居中

.father {
            display: flex;
            justify-content: center;
            align-items: center;
            width: 500px;
            height: 300px;
            background-color: skyblue;
            margin: 0 auto;
        }

        .son {
            width: 100px;
            height: 100px;
            background-color: pink;
        }