DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> CSS詳解
三種有效解決 DIV 高度自適應的方法
編輯:CSS詳解     

DIV+CSS 儼然已成網頁設計的主流,好處大家都清楚,但有些小問題確實棘手,最典型的莫過於「DIV 高度自適應」。以下整理三種行之有效的解法。

1. JavaScript 法

原理很直接:用 JS 比較左右兩欄的高度,若不一致就設為一致。

<div style="width:500px; background:#cccccc; height:0px;">
  <div id="right" style="width:38%; height:100%;
       float:left; border:1px solid #265492;">left</div>
  <div id="left" style="width:60%; float:left; background:#376037;">
    right<br>
    right<br>
    right<br>
    right<br>
    right<br>
    right<br>
    right<br>
  </div>
</div>

<script type="text/javascript">
var a = document.getElementById("left");
var b = document.getElementById("right");
if(a.clientHeight < b.clientHeight){
  a.style.height = b.clientHeight + "px";
} else {
  b.style.height = a.clientHeight + "px";
}
</script>

優點是精準;缺點是依賴 JavaScript,禁用 JS 時失效,且視窗縮放後需要重新計算。

2. 背景圖填充法

這是大網站常用的做法。核心思路是:給父層容器設一張背景圖,所有子欄位都不設高度,視覺上的「欄位填滿」其實來自父層的背景。

HTML:

<div class="endArea">
  <div class="col1">第一列 左邊正文</div>
  <div class="col3">第二列 右邊</div>
  <div class="col2">第三列 中間圖片</div>
  <div class="clear"></div>
</div>

CSS:

.endArea{
  margin:0 auto;
  width:960px;
  background:url(bg.gif);
  clear:both;
}

.endArea .col1{ float:left; width:573px; }
.endArea .col2{ float:left; width:25px; }
.endArea .col3{ float:right; width:362px; }

優點是不依賴 JS、相容性極佳;缺點是欄位寬度被背景圖鎖死,屬於彈性換取穩定性的取捨。

3. 補丁大法

這是最另類的一種,結合了「隱藏容器溢出」與「正內距搭配負外距」的技巧,在 IE6、IE7、Firefox 3 下測試通過。

要點:

  1. 父層 DIV 設定 overflow:hidden;
  2. 對要自適應的 DIV 設定 padding-bottom:100000px; margin-bottom:-100000px;,兩欄或多欄同理。

程式碼:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=gb2312"/>
<title>補丁大法示範</title>
<style type="text/css">
#wrap{ overflow:hidden; }
#sidebar_left, #sidebar_right{
  padding-bottom:100000px;
  margin-bottom:-100000px;
}
</style>
</head>
<body>
<div id="wrap" style="width:300px; background:#FFFF00;">
  <div id="sidebar_left" style="float:left; width:100px;
       background:#777;">Left</div>
  <div id="sidebar_mid" style="float:left; width:100px;
       background:#999;">Middle</div>
  <div id="sidebar_right" style="float:right; width:100px;
       background:#888;">Right</div>
</div>
</body>
</html>

原理是:用極大的下方內距把欄位撐長,再用等量的負外距把版面拉回來,最後由父層的 overflow:hidden 裁掉多餘部分。視覺上所有欄位就一樣高了。

該選哪一種?

如果欄寬固定、設計稿不會變,背景圖填充法最穩。如果需要 JS 之外的純 CSS 彈性解法,補丁大法很有效。若專案本來就重度依賴 JavaScript,第一種最直觀。

補充一個現代解法:若你的專案不受舊瀏覽器限制,直接用 display:flex 或 display:grid,等高的問題會自動消失,完全不需要上述任何技巧。這是首選,只是過去受限於相容性無法使用。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved