萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

側邊欄背景色延伸至頁腳解決方案:從背景圖偽裝到 Flexbox/Grid 等高佈局

問題場景

左側導航欄背景色需延伸至頁腳,但內容高度不固定,傳統 background-color 只覆蓋內容區高度。

方案演進

1. 偽裝法:Body 背景圖重複

body { background: url(sidebar-bg.png) repeat-y 0 0; }
#sidebar { width: 200px; float: left; }

缺點:固定寬度、無法用 em/rem、圖片維護麻煩。

2. 負 Margin + Padding 大法

.wrapper { overflow: hidden; }
#sidebar { float: left; width: 200px; margin-bottom: -9999px; padding-bottom: 9999px; }

缺點:極大數值可能觸發瀏覽器渲染 Bug、錨點定位偏移。

3. Flexbox 等高(推薦)

.container { display: flex; }
#sidebar { width: 200px; background: #333; }
#main { flex: 1; }

優點:自動等高、無 Hack、支援任意欄數。

4. Grid 定義行高

.container { display: grid; grid-template-columns: 200px 1fr; grid-template-rows: 1fr auto; }
#sidebar { grid-row: 1 / 3; background: #333; } /* 跨 header/main/footer */
#header { grid-column: 1 / 3; }
#footer { grid-column: 1 / 3; }

5. CSS Tables(IE8+)

.container { display: table; width: 100%; }
#sidebar, #main { display: table-cell; vertical-align: top; }

選擇建議

  • 現代專案:**Flexbox** 最通用、**Grid** 最強大。
  • 需支援 IE10-:Flexbox + Autoprefixer。
  • 極舊專案維護:負 Margin 或背景圖偽裝。
copyright © 萬盛學電腦網 all rights reserved