定位方法实现水平垂直居中

eg.png

html代码:

css代码:

        .end{
            width: 500px;
            height:500px;
            border:1px solid red;
            position: relative;
        }
        .to-center{
            width: 200px;
            height:200px;
            background:green;
            position: absolute;
            top:50%;
            left:50%;
            transform: translate(-50%,-50%);/*同理:margin-left: -100px;margin-top: -100px;*/
                      
        }

先使用定位,将这个绿色盒子定位到离上面50%,离左边50%的位置上,然后再使用transform 优雅降级 将盒子多移出去的一半大小减去即可完成。

你可能感兴趣的:(定位方法实现水平垂直居中)