三個同高 div,中間寬度固定(如 960px),左右兩側平分剩餘空間,隨視口變化自適應。
.container {
display: flex;
height: 300px; /* 或 100vh */
}
.left, .right {
flex: 1; /* 平分剩餘空間 */
background: #eee;
}
.center {
width: 960px; /* 固定寬度 */
flex-shrink: 0; /* 防止被壓縮 */
background: #fff;
}
.container {
display: grid;
grid-template-columns: 1fr 960px 1fr; /* 左中右 */
height: 300px;
}
.container { overflow: hidden; height: 300px; }
.center { width: 960px; margin: 0 auto; background: #fff; }
.left, .right { width: 50%; float: left; height: 100%; }
.left { margin-left: -960px; background: #eee; } /* 複雜,不推薦新項目使用 */
function resize() {
var w = document.documentElement.clientWidth || document.body.clientWidth;
var side = (w - 960) / 2;
document.querySelector('.left').style.width = side + 'px';
document.querySelector('.right').style.width = side + 'px';
}
window.onresize = resize;
resize();
缺點:需監聽 resize、重排重繪、JS 執行延遲導致閃爍,維護成本高。
| 場景 | 推薦方案 | 理由 |
|---|---|---|
| 現代項目(IE10+) | Flexbox | 語法簡潔、彈性強、無副作用 |
| 需精確控制列數/間距 | Grid | 二維佈局原生支持、代碼可讀性高 |
| 必須兼容 IE9 | Float + 負 Margin 或 JS | 無現代 CSS 支持時的妥協方案 |
align-items: stretch 實現等高overflow-x: auto 內部滾動,避免撐破佈局overflow: auto 或 hidden