讓兩列Div一樣高(自適應高度)

    由於設計頁面需要,要把兩個並排顯示的div實現一樣高的效果,n行n列布局,每列高度(事先並不能確定哪列的高度)的相同,是每個設計師追求的目標。方法有以下幾種:1、JS實現(判斷2個div高);2、純css方法;3、加背景圖片實現。首先說下本博客實現的2個div一樣高的方法(即js方法)。

    div css基本佈局:

<div id="mm">
<div id="mm1"></div>
<div id="mm2"></div>
</div>

    1、js實現div自適應高度

代碼如下:
<script type="text/javascript">
<!--
window.οnlοad=window.οnresize=function(){
if(document.getElementById("mm2").clientHeight<document.getElementById("mm1").clientHeight){
document.getElementById("mm2").style.height=document.getElementById("mm1").offsetHeight "px";
}
else{
document.getElementById("mm1").style.height=document.getElementById("mm2").offsetHeight "px";
}
}
-->
</script>

    (注:網上公佈了不少方法,但代碼或多或少有錯;上面的是無錯代碼;我測試在IE6.0/IE7.0下通過,考慮絕大數人仍然用的是IE,所以並沒有在opera和firefoxs下調試,哪位用的是opera或ff,可以幫忙看看飄易博客的DIV是否保持了一致的高度。)

    2、純CSS方法

    css裏代碼(調試通過,但不會顯示div下邊框,即border-bottom):

/*左右自適應相同高度start*/
#m1,#m2
{
padding-bottom: 32767px !important;
margin-bottom: -32767px !important;
}
@media all and (min-width: 0px) {
#m1,#m2
{
padding-bottom: 0 !important;
margin-bottom: 0 !important;
}
#m1:before, #m2:before
{
content: '[DO NOT LEAVE IT IS NOT REAL]';
display: block;
background: inherit;
padding-top: 32767px !important;
margin-bottom: -32767px !important;
height: 0;
}
}
/*左右自適應相同高度end*/


    3、加背景圖片

    這個方法,很多大網站在使用,如163,sina等。

    XHTML代碼:

<div id="wrap">
<div id="column1">這是第一列</div>
<div id="column1">這是第二列</div>
<div class="clear"></div>
</div>

    CSS代碼:

#wrap{ width:776px; background:url(bg.gif) repeat-y 300px;}
#column1{ float:left; width:300px;}
#column2{ float:right; width:476px;}
.clear{ clear:both;}

發佈了1 篇原創文章 · 獲贊 4 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章