美文网首页
css居中总结

css居中总结

作者: solfKwolf | 来源:发表于2017-11-03 21:33 被阅读7次
    <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;
            }
    

    参考资料:

    相关文章

      网友评论

          本文标题:css居中总结

          本文链接:https://www.haomeiwen.com/subject/agjxmxtx.html