css居中总结

2017-11-03  本文已影响7人  solfKwolf
<div id="box"></div>

1.绝对定位实现居中

#box{
            position: absolute;
            top: 50%;
            left: 50%;
            width: 100px;
            height: 100px;
            margin-top: -50px;
            margin-left: -50px;
            background-color: red;
        }

缺点:必须知道box的宽高,否则无法确定!

2.CSS3的做法

#box{
            width: 100px;
            height: 100px;
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%,-50%);
            background-color: red;
        }

3.absolute和margin:auto;

#box{
            position: absolute;
            left: 0;
            top: 0;
            right: 0;
            bottom: 0;
            width: 100px;
            height: 100px;
            margin: auto;
            background-color: red;
        }

参考资料:

上一篇 下一篇

猜你喜欢

热点阅读