萬盛學電腦網

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

CSS 讓 body 背景圖片水平垂直置中並固定

核心 CSS

html, body { height: 100%; margin: 0; }
body {
  background: #fff url(bg.jpg) center center / cover no-repeat fixed;
  /* 等價於:
  background-color: #fff;
  background-image: url(bg.jpg);
  background-position: center center;
  background-size: cover;
  background-repeat: no-repeat;
  background-attachment: fixed;
  */
}

關鍵點解析

  • html, body { height: 100% }:確保 body 高度至少滿視口,背景才能垂直置中於可視區域。
  • background-position: center center:水平垂直雙向置中。
  • background-size: cover:圖片等比縮放覆蓋全區域(可改 contain 完整顯示)。
  • background-attachment: fixed:背景相對視口固定,滾動時產生視差效果(可選)。

完整頁面範本

<!DOCTYPE html>
<html lang="zh-Hant">
<head>
  <meta charset="utf-8">
  <title>Body 背景置中示例</title>
  <style>
    html, body { height: 100%; margin: 0; }
    body { background: #fff url("https://example.com/bg.jpg") center/cover no-repeat fixed; }
    .wrap { max-width: 800px; margin: 0 auto; padding: 40px 20px; background: rgba(255,255,255,.85); }
  </style>
</head>
<body>
  <div class="wrap">
    <h1>內容區域</h1>
    <p>背景圖固定置中,內容正常滾動...</p>
  </div>
</body>
</html>

行動裝置提醒

iOS Safari 對 background-attachment: fixed 在 body 上支援有問題(會隨內容滾動),建議:

@media (max-width: 768px) {
  body { background-attachment: scroll; }
}

或改用固定定位偽元素:

body::before {
  content: ""; position: fixed; inset: 0; z-index: -1;
  background: url(bg.jpg) center/cover no-repeat;
}
copyright © 萬盛學電腦網 all rights reserved