定位控制元素水平垂直居中

发布时间 2023-10-13 17:00:31作者: 故塔拉黑暗之神

浏览器中盒子的位置

1.使用绝对元素,相对于浏览器第一窗口进行50%的距离设置,盒子会移动到第四象限;

 再使用外边距设置让盒子移动到中间位置(注意正负值的设置)

 *{margin: 0;
         padding: 0;
        }
        div{
            width:200px;
            height:200px;
            background: yellowgreen;
            position: absolute;
            top:50%;
            left: 50%;
            margin-top: -100px;
            margin-left: -100px;
        }

父盒子中子盒子的位置

方法同上,但是位置变化是相对于父盒子

*{margin: 0;
         padding: 0;
        }
        .box{
            width:500px;
            height:500px;
            background: yellowgreen;
            position:relative
        }
        .child{
            width:200px;
            height:200px;
            background: red;
            position:absolute;
        }