左側 300×250px 廣告位,右側文章內容。文章高度超過 250px 時,內容不應環繞廣告下方,而應始終保持左右兩欄獨立佈局。
<div class="container">
<div class="ad-sidebar" style="float: left; margin-right: 15px; width: 300px; height: 300px;">
<!-- 廣告內容 -->
</div>
<div class="article-content">
<!-- 文章內容,高度不確定 -->
</div>
</div>
缺點:需硬編碼高度、內容超高仍會環繞、需額外 clearfix、響應式困難。
.container { overflow: hidden; } /* 或 .clearfix */
.ad-sidebar { float: left; width: 300px; margin-right: 15px; }
.article-content { overflow: hidden; } /* 觸發 BFC,不環繞浮動元素 */
原理:overflow: hidden 建立新的 BFC(塊級格式化上下文),BFC 內部元素不會與外部浮動元素重疊。
.container {
display: flex;
gap: 15px; /* 替代 margin-right */
align-items: flex-start; /* 頂部對齊,不拉伸 */
}
.ad-sidebar {
flex: 0 0 300px; /* 固定 300px,不縮放 */
/* 或 min-width: 300px; max-width: 300px; */
}
.article-content {
flex: 1; /* 佔據剩餘空間 */
min-width: 0; /* 關鍵:允許內容壓縮換行 */
}
.container {
display: grid;
grid-template-columns: 300px 1fr; /* 固定 300px + 自適應 */
gap: 15px;
align-items: start; /* 頂部對齊 */
}
.container { display: table; width: 100%; }
.ad-sidebar { display: table-cell; width: 300px; padding-right: 15px; }
.article-content { display: table-cell; vertical-align: top; }
/* 移動端:單欄堆疊,廣告上移或下沉 */
@media (max-width: 768px) {
.container {
flex-direction: column; /* Flex 方案 */
/* grid-template-columns: 1fr; */ /* Grid 方案 */
}
.ad-sidebar {
flex: none; width: 100%; /* 恢復自適應寬度 */
margin-right: 0;
margin-bottom: 15px;
}
}
.rect {
width: 300px;
height: 150px;
border: 1px solid #000;
}
.split-container {
display: flex;
height: 150px;
}
.split-left {
flex: 1;
border-right: 1px solid #000; /* 右邊框做分割線 */
box-sizing: border-box;
}
.split-right {
flex: 1;
}
/* 或使用偽元素畫線(不影響內容區) */
.split-container::before {
content: "";
position: absolute;
left: 50%; top: 0; bottom: 0;
border-left: 1px solid #000;
transform: translateX(-50%);
}
| 方案 | 兼容性 | 靈活度 | 維護性 | 推薦場景 |
|---|---|---|---|---|
| Float + BFC | IE6+ | 低 | 差 | 極老專案維護 |
| Table Display | IE8+ | 中 | 中 | 需支援 IE8-9 |
| Flexbox | IE10+ | 高 | 好 | ✅ 現代主流首選 |
| Grid | IE10+ (部分) | 最高 | 最好 | 二維佈局、複雜對齊 |
height 硬撐佈局gap 替代 margin 控制間距min-width: 0 防止 Flex 子項溢出