前言
其實在 CSS 裡,zoom 這個屬性一直不太為人所知,甚至有些 CSS 手冊都查不到它。說穿了,zoom 是 IE 瀏覽器的專有屬性,Firefox 等瀏覽器並不支持。它能設定或取得物件的縮放比例;除此之外,它還有其他妙用,比如觸發 IE 的 hasLayout 屬性、清除浮動、消除 margin 重疊等。
正因為 zoom 是 IE 的專有屬性,所以它清除浮動的作用只適用於 IE 瀏覽器;而 Firefox、Chrome 等瀏覽器則得改用 overflow: auto 屬性來清除浮動。因此,若要同時相容 IE6、IE7、IE8、Firefox 與 Chrome,就必須把這兩個屬性搭配使用。
我們在重構頁面時,經常會用到「一個大容器包著多個浮動小容器」的版面配置。但如果外層這個大容器沒有設定固定高度,它的高度就不會隨著內部小容器的高度變化而變化,於是便會出現內容溢出的現象,這時只要清除浮動就能恢復正常。所以,只要給外層大容器加上 overflow: auto,就能解決 IE7 與 Firefox 下的清除浮動問題;但它在 IE6 下不生效,因此我們還得借助 zoom 這個 IE 私有屬性,才能達到徹底相容的清除浮動效果。
實例程式碼
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>MJBlog</title>
<style type="text/css">
.box { width: 300px; height: auto; background-color: #000000; margin: 100px auto; padding: 5px; }
.box h2 { width: 300px; line-height: 24px; color: #CCCCCC; }
.xx { width: 140px; float: left; height: 24px; overflow: hidden; padding: 0px 5px; line-height: 24px; color: #FF9933; }
.za { overflow: auto; zoom: 1; }
.zb { overflow: auto; }
.zc { zoom: 1; }
</style>
</head>
<body>
<div class="box">
<h2>這個沒加 overflow:auto 和 zoom:1 屬性,沒有清除浮動,底下的 li 產生溢出重疊現象</h2>
<div class="xx">福州酒吧萬聖節派對活動</div>
<div class="xx">福州酒吧萬聖節派對活動</div>
<div class="xx">福州酒吧萬聖節派對活動</div>
<div class="xx">福州酒吧萬聖節派對活動</div>
<div class="xx">福州酒吧萬聖節派對活動</div>
<div class="xx">福州酒吧萬聖節派對活動</div>
</div>
<div class="box za">
<h2>這個加 overflow:auto 和 zoom:1 屬性,清除浮動,正常</h2>
<div class="xx">福州酒吧萬聖節派對活動</div>
<div class="xx">福州酒吧萬聖節派對活動</div>
<div class="xx">福州酒吧萬聖節派對活動</div>
<div class="xx">福州酒吧萬聖節派對活動</div>
<div class="xx">福州酒吧萬聖節派對活動</div>
<div class="xx">福州酒吧萬聖節派對活動</div>
</div>
</body>
</html>
總結
以上就是關於 CSS 中 zoom 屬性與 overflow: auto 屬性清除浮動作用的全部內容,希望本文能對大家的工作或學習有所幫助。如果有疑問,歡迎留言交流,也謝謝大家的支持。