利用box-flex實現 dom元素位置頁面底部


問題:

總是有這樣的需求,就是頁面上某部分要位於頁面的最底部,此“最底部”要求:(1)當頁面上內容不足一屏的時候,在最底部顯示(2)當頁面上內容不止一屏的時候,也就是有垂直滾動條的時候,要在內容的最后顯示

最容易想到的定位方法:

(1)position:absolute  

position:absolute;
bottom:0;
left:0

此種方法只能把該元素定位到第一屏的最底部,它並不會隨着滾動條的出現跑到內容的最后面去。滿足(1)不滿足(2)

(2)position:relative

此種方法只能滿足(2),不能滿足(1),當然要滿足(1)的話,可以配合使用js, 思路是利用JS計算屏幕高度,減去底部高度,設定除底部的其他元素的高度。

最簡單的方法(需要支持CSS3的box-flex屬性):

關於box-flex的詳細講解請看:http://www.zhangxinxu.com/wordpress/2010/12/css-box-flex%E5%B1%9E%E6%80%A7%EF%BC%8C%E7%84%B6%E5%90%8E%E5%BC%B9%E6%80%A7%E7%9B%92%E5%AD%90%E6%A8%A1%E5%9E%8B%E7%AE%80%E4%BB%8B/

利用box-flex屬性就可以實現上面提到的需求,見下面的代碼:

<style>
    
    .con{
        position: absolute;
        height: 100%;
        width: 100%;
        top:0;bottom: 0;left: 0;right: 0px
    }
    .wrap{
        
        min-height: 100%;
        width: 100%;
        position: relative;
        
        /**父元素display設置為box**/
        display:-moz-box; 
        display:-webkit-box; 
        display:-o-box; 
        display:box;

        /**父元素的布局是垂直方向**/
        -moz-box-orient:vertical; 
        -webkit-box-orient:vertical; 
        -o-box-orient:vertical; 
        box-orient:vertical; 

        -moz-box-align:center; 
        -webkit-box-align:center; 
        -o-box-align:center; 
        box-align:center; 

        -moz-box-pack:center; 
        -webkit-box-pack:center; 
        -o-box-pack:center; 
        box-pack:center;      
    }
    .main{
        background-color: blue;
        color: #fff;
        width: 100%;
         -moz-box-flex: 1; 
        -webkit-box-flex: 1; 
        box-flex: 1;
    }
    .footer{
        background-color: green;
        width:100%;
        height: 30px;
    }
    </style>
    <div class="con">
        <div class="wrap">
            <div class="main"></div>
            <div class="footer"></div>
        </div>
    </div>

這樣,footer 就以30px的像素告訴一直位於頁面的底部,並且滿足(1),滿足(2)

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM