匯總兩大高頻需求:跨瀏覽器 CSS Hack 與浮動清除,提供最小化、最高頻的代碼片段。
!important 區分 IE6#wrapper {
width: 100px !important; /* 現代瀏覽器 & IE7+ 讀取 */
width: 80px; /* IE6 讀取(忽略 !important) */
}
鐵律:!important 聲明必須寫在前面。
#wrapper { width: 120px; } /* 現代瀏覽器 & Firefox */
*html #wrapper { width: 80px; } /* IE6 及以下 */
*+html #wrapper { width: 60px; } /* 僅 IE7 */
前提:頁面必須聲明標準 DOCTYPE(如 XHTML 1.0 Transitional),否則 *+html 在 IE7 不生效。
加入全局 CSS,需閉合的容器加 class="clearfix":
.clearfix:after {
content:".";
display:block;
height:0;
clear:both;
visibility:hidden;
}
.clearfix {
display:inline-block; /* IE/Mac */
}
.clearfix {
display:block; /* 觸發 IE6/7 hasLayout */
}
<div class="container clearfix">
<div class="float-left">左欄</div>
<div class="float-right">右欄</div>
</div>
.container { display:flow-root; }(現代標準).container { display:flex; }(Flex 佈局自動包含浮動).container { overflow:hidden; }(簡單場景,注意陰影/外邊距被裁切)clear:both 僅影響同級後續元素,不影響父層高度(除非父層建立 BFC)