浮动元素居中

作者: 鸭梨山大哎 | 来源:发表于2017-07-01 20:24 被阅读58次

    怎么才能使浮动元素居中呢?

    浮动可以left,right 就是没有中间啊。那怎么办呢?
    可以设置一个中间的基线。也就是给浮动元素先设置一个父元素。

    <meta charset="utf-8">
    <style> 
    .box {
        border:2px solid green;
        float:left;
        position:relative;
        left:50%;/*move to right 50% of the window width*/
    }   
    p { 
        border:2px solid red;
        position: relative;
    }   
    
    </style>
    <div class="box">
     <p>我是浮动的</p>
    </div>
    

    结果

    image.png

    之后由于父元素和子元素的宽度是一样的。再让子元素相对于其正常位置(如上图位置)向左移动其宽度的50%.就实现了子元素居中。

    <meta charset="utf-8">
    <style> 
    .box {
        float:left;
        position:relative;
        left:50%;/*move to right 50% of the window width*/
    }   
    p { 
        border:2px solid red;
        position: relative;
        right:50%;/*move to left 50% of the box width*/
    
    }   
    
    </style>
    <div class="box">
     <p>我是浮动的</p>
    
    </div>
    

    结果

    image.png

    总结

    父元素和子元素同时左浮动,然后父元素相对左移动50%,再然后子元素相对右移动50%。就实现了浮动元素居中。

    参考

    css如何让浮动元素水平居中javascript技巧脚本之家

    相关文章

      网友评论

        本文标题:浮动元素居中

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