DIV高度自適應,這是在網頁設計中常遇到的問題,爲了給你們提供參考,這裏提供3種div高度自適應的方法:一是JS法、二是背景圖填充法、三是「補丁大法」(比較變態)。javascript
一、JS法css
代碼以下。原理:用JS判斷左右DIV的高度,若不一致則設爲一致。html
01 |
< div style = "width:500px;background:#cccccc;height:0px;" > |
02 |
< div id = "right" style = "width:380%;height:100%;float:left;border:1px solid #265492;" >left</ div > |
03 |
< div id = "left" style = "width:60%;;float:left;background:#376037;" > |
04 |
right< br > |
05 |
right< br > |
06 |
right< br > |
07 |
right< br > |
08 |
right< br > |
09 |
right< br > |
10 |
right< br > |
11 |
</ div > |
12 |
</ div > |
13 |
< script type = "text/javascript" > |
14 |
<!-- |
15 |
var a=document.getElementById("left"); |
16 |
var b=document.getElementById("right"); |
17 |
if(a.clientHeight<b.clientHeight){ |
18 |
a.style.height=b.clientHeight+"px"; |
19 |
}else{ |
20 |
b.style.height=a.clientHeight+"px"; |
21 |
} |
22 |
--> |
23 |
</ script > |
二、背景圖填充法java
這是大站用得比較多的方法,如163等,研究了一下,結果以下。ide
這裏是給父DIV設置了背景圖片填充,全部DIV都不設高度。測試
HTML代碼:ui
1 |
< div class = "endArea" > |
2 |
< div class = "col1" >第一列 左邊正文</ div > |
3 |
< div class = "col3" >第二列 右邊< br />< br />< br />< br />< br />< br />< br />< br />< br />< br />< br />字字</ div > |
4 |
< div class = "col2" >第三列 中間圖片</ div > |
5 |
< div class = "clear" ></ div > |
6 |
</ div > |
CSS代碼:url
1 |
.endArea{ margin : 0 auto ; width : 960px ; background : url (http://cimg 2.163 .com/cnews/img 07 /end_n_bg 1 .gif); clear : both ;} |
2 |
.endArea .col 1 { float : left ; width : 573px ; } |
3 |
.endArea .col 2 { float : left ; width : 25px ; } |
4 |
.endArea .col 3 { float : right ; width : 362px ;} |
三、補丁大法spa
就是「隱藏容器溢出」和「正內補丁」和「負外補丁」結合的方法。比較另類的方法,在IE六、IE七、FF3下測試經過。要點:設計
一、父DIV設置 overflow:hidden;
二、對要高度自適應的DIV設置 padding-bottom:100000px;margin-bottom:-100000px; 兩列或多列同理。
代碼以下:
01 |
< html > |
02 |
< head > |
03 |
< meta http-equiv = "Content-Type" content = "text/html; charset=gb2312" /> |
04 |
< title >Div高度自適應</ title > |
05 |
< style type = "text/css" > |
06 |
#wrap{overflow:hidden;} |
07 |
#sidebar_left,#sidebar_right{padding-bottom:100000px;margin-bottom:-100000px;} |
08 |
</ style > |
09 |
</ head > |
10 |
< body > |
11 |
< div id = "wrap" style = "width:300px; background:#FFFF00;" > |
12 |
< div id = "sidebar_left" style = "float:left;width:100px; background:#777;" >居左</ div > |
13 |
< div id = "sidebar_mid" style = "float:left;width:100px; background:#999;" > |
14 |
居中< br /> |
15 |
居中< br /> |
16 |
居中< br /> |
17 |
居中< br /> |
18 |
居中< br /> |
19 |
居中< br /> |
20 |
居中< br /> |
21 |
</ div >< div id = "sidebar_right" style = "float:right;width:100px; background:#888;" >居右</ div ></ div > |
22 |
</ body > |
23 |
</ html > |
以上三種方法均可以解決Div高度自適應,請根據你本身的須要,三選一。