div 的寬度 100% ≠ 100% (IE 6&7)需求:
- 標準模式
- #container 局部滾動
- #asie 固定寬度
- #content 自適應寬度
再複雜一點還會要求兩列等高,可參考 http://www.99css.com/?p=40
HTML
<div id="container"> <div id="wrapper"> <div id="content"> <h2>Content</h2> </div> </div> <div id="aside"> <h2>Aside</h2> </div></div>
當然,別忘了 DTD 聲明,因為這個只存在於標準模式
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
用之前介紹的HTML5 寫法亦可:
<!DOCTYPE html>
CSS
/*簡單重設*/body, div, h2{margin:0;padding:0;}/*設定顏色,方便區分*/#container{background:yellow;}#content{background:#FF8539;}#aside{background:#B9CAFF;}/*去除html預設捲軸*/html{overflow-y:hidden;}/*關鍵布局代碼*/#container{height:300px;overflow:auto;}#wrapper{float:left;width:100%;margin-left:-200px;}#content{margin-left:200px;}#aside{float:right;width:200px;}
當#content, #aside{height:200px;}時,即高度未超出#container時一切正常
當#content, #aside{height:400px;}時,出現縱向捲軸
正常顯示效果如下:
IE 6&7 中 bug 出現:
原因:IE 6&7 捲軸的寬度未算在 100% 中,理想的狀況是:#container 的寬度(100%) + #container 捲軸的寬度
= body 的 100%,W3C對此的定義:
In the case of a scrollbar being placed on an edge of the element’s box,
it should be inserted between the inner border edge and the outer padding
edge. Any space taken up by the scrollbars should be taken out of (subtracted
from the dimensions of) the containing block formed by the element with
the scrollbars.
《Internet Explorer 100% Width Bug》中給出了思路:
element_selector {width: expression(this.parentNode.offsetHeight >this.parentNode.scrollHeight ? '100%' :parseInt(this.parentNode.offsetWidth - XX) + 'px');}
其中 XX 是捲軸的寬度,在 Windows XP 主題下是 17px,Windows 經典主題下稍微小一點,在其他第三方系統主題下有可能是不確定寬度。
根據,簡單改進一下即可
解決方案
#wrapper{#width:expression(this.parentNode.offsetHeight > this.parentNode.scrollHeight ? '100%' : parseInt(this.parentNode.clientWidth) + 'px');}
當然,寫在 js 中亦可,不過要注意不要漏掉 window 的 riseze 事件,另外,window 的 resize 事件在 IE 中有執行多次的
bug