在 IE6 中設定絕對定位時,left 與 bottom 常會出現錯位。本文透過一段對比程式碼,說明現代瀏覽器與 IE6 的差異,並附上有效的解決方案。
以下範例可幫助你理解問題所在,建議搭配 firebug 除錯,動手改改看幾個樣式:
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>測試模型</title>
<link href="css/test.css" type="text/css" rel="stylesheet" />
<style>
</style>
<script src="js/jquery-1.7.2.min.js" type="text/javascript"></script>
</head>
<body style="width:900px;margin:0 auto 800px auto;">
<p>IE6 下的 left 定位錯誤</p>
<div style="position:relative; border:1px solid orange; text-align:center;">
<span>父級 div,文本居中</span>
<div style="position:absolute;top:0;left:0;background:#CCC;">文本居中的子元素 div,絕對定位 top:0;left:0;</div>
</div>
<hr />
<div style="position:relative; border:1px solid orange; text-align:right;">
<span>父級 div,文本居右</span>
<div style="position:absolute;top:0;left:0;background:#CCC;">文本居右的子元素 div,絕對定位 top:0;left:0;</div>
</div>
<hr/>
<p>IE6 下 left 定位錯誤的解法 1:父級加上 zoom:1;</p>
<div style="position:relative; border:1px solid orange; text-align:center;zoom:1;">
<span>父級 div,文本居中,加了 zoom:1;</span>
<div style="position:absolute;top:0;left:0;background:#CCC;">文本居中的子元素 div,絕對定位 top:0;left:0;</div>
</div>
<hr/>
<p>IE6 下 left 定位錯誤的解法 2:父級加上 width;</p>
<div style="position:relative;border:1px solid orange;text-align:right;width:99%;">
<span>父級 div,文本居右,加了 width:99%;</span>
<div style="position:absolute;bottom:0;left:0;background:#CCC;">文本居右的子元素 div,絕對定位 bottom:0;left:0;</div>
</div>
<hr/>
<p>IE6 下的 bottom 定位錯誤</p>
<div style="position:relative;border:1px solid orange;text-align:center;">
<span>父級 div,文本居中</span>
<div style="position:absolute;bottom:0;left:0;background:#CCC;">bottom 定位錯位了</div>
</div>
<hr/>
<p>IE6 下 bottom 定位錯誤的解法 1:父級加上 zoom:1;</p>
<div style="position:relative;border:1px solid orange;text-align:center;zoom:1;">
<span>父級 div,文本居中,加了 zoom:1;</span>
<div style="position:absolute;bottom:0;left:0;background:#CCC;">bottom 定位</div>
</div>
<hr/>
<p>IE6 下 bottom 定位錯誤的解法 2:父級加上 height;</p>
<div style="position:relative;border:1px solid orange;text-align:right;height:60px;">
<span>父級 div,文本居右,加了 height:60px;</span>
<div style="position:absolute;bottom:0;left:0;background:#CCC;">bottom 定位</div>
</div>
</body>
</html>
IE6 的許多 Bug 都能透過「觸發 layout」來解決。無論是 zoom:1 還是設定 width、height,本質上都是為了觸發 layout。只要觸發了 layout,left 或 bottom 的錯位問題就能正常定位。
以下 CSS 屬性或取值會讓元素獲得 layout:
position:absolute(絕對定位元素的包含區塊常在此出問題)
float:left|right(浮動模型有許多怪異表現)
display:inline-block
width: 除 auto 外的任何值
height: 除 auto 外的任何值
zoom: 除 auto 外的任何值