萬盛學電腦網

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

CSS 實現 Body 背景圖全螢幕自適應(不限解析度)

核心技巧:固定定位 + 100% 寬高 + 負 z-index

<body>
  <img id="bg" src="../images/bg.jpg"
       width="100%" height="100%"
       style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; z-index: -1;" />
  ...頁面內容...
</body>

關鍵點解析

  • position: fixed:相對視窗定位,不隨頁面捲動。
  • top/left/right/bottom: 0:四邊貼齊視窗邊緣。
  • width/height: 100%:撐滿整個視窗。
  • z-index: -1:置於所有內容底層。

現代 CSS3 純樣式方案(推薦)

body {
  background: url('../images/bg.jpg') center center / cover no-repeat fixed;
  /* background-size: cover 保證圖片填滿且保持比例 */
  /* background-attachment: fixed 產生視差感(可選) */
}

優點:無額外 DOM、效能更好、支援響應式、可搭配多重背景、漸層疊加。

回應式補充

若需在小螢幕載入較小圖片,可用 @media 配合 image-set() 或 <picture> 元素實現美術導向適配。

copyright © 萬盛學電腦網 all rights reserved