zl程序教程

您现在的位置是:首页 >  后端

当前栏目

css练习:让一个元素垂直水平居中的四种方法

方法CSS 一个 元素 练习 四种 水平 居中
2023-09-14 09:04:08 时间

参考:

https://www.cnblogs.com/linsinan/p/6132241.html

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>demo</title>
    <style>
        div.box1 {
            weight: 200px;
            height: 400px;
            background-color: deeppink;
        <!-- 把元素变成定位元素-- > position: absolute;
        <!-- 设置元素的定位位置,距离上、左都为50 % --> left: 50%;
            top: 50%;
        <!-- 设置元素的左外边距、上外边距为宽高的负1 / 2 --> margin-left: -100px;
            margin-top: -200px;
        }

        div.box2 {
            weight: 200px;
            height: 400px;
            background-color: hotpink;
        <!-- 把元素变成定位元素-- > position: absolute;
        <!-- 设置元素的定位位置,距离上、左都为50 % --> left: 50%;
            top: 50%;
        <!-- 设置元素的相对于自身的偏移度为负50 %(也就是元素自身尺寸的一半) --> transform: translate(-50%, -50%);

        }

        div.box3 {
            width: 200px;
            height: 400px;
            background-color: blue;
            /*<!-- 把元素变成定位元素-- > */
            position: absolute;
            /*<!-- 设置元素的定位位置,距离上、下、左、右都为0-- > */
            left: 0;
            right: 0;
            top: 0;
            bottom: 0;
            /*<!-- 设置元素的margin样式值为 auto-- > */
            margin: auto;
        }

        .A {
            width: 500px;
            background-color: green;
            text-align: center;
        }

        .B {
            width: 100px;
            height: 100px;
            margin: 5px;
            background-color: dodgerblue;
            display: inline-block;
        }
    </style>
</head>
<body>
    <div class="box1">
    111
    </div>
    <div class="box2">
    222
    </div>
    <div class="box3">
    333
    </div>
    <div class="A">
        <div class="B"></div>
        <div class="B"></div> 
        <div class="B"></div>
    </div>
</body>
</html>

效果: