Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> CSS

Background Attachment (Đính kèm nền) trong CSS

Thuộc tính background-attachment trong CSS được dùng để chỉ định vị trí của hình ảnh nền khi trang được cuộn (scroll) tương đối với viewport. Nó có thể nhận các giá trị: scroll, fixed và local.

Cú pháp

Selector {
  background-attachment: /*value*/
}

Ví dụ 1: background-attachment: local

<!DOCTYPE html>
<html>
<head>
<style>
  body {
    background-repeat: no-repeat;
    background-attachment: local;
    background-position: center;
    background-image: url("https://www.tutorialspoint.com/power_bi/images/power-bi-mini-logo.jpg");
  }
  div { padding: 40px; margin: 30px; }
  .in { background: rgba(0,0,0,0.4); }
</style>
</head>
<body>
  <div id="one">
    <div class="in"></div><div class="in"></div><div class="in"></div>
    <div class="in"></div><div class="in"></div>
  </div>
</body>
</html>

Kết quả

Ban đầu:

Background Attachment (Đính kèm nền) trong CSS

Khi cuộn (scroll):

Background Attachment (Đính kèm nền) trong CSS

Ví dụ 2: background-attachment: fixed

<!DOCTYPE html>
<html>
<head>
<style>
  body {
    background-repeat: no-repeat;
    background-attachment: fixed;
    background-position: 10% 5%;
    background-image: url("https://www.tutorialspoint.com/power_bi/images/power-bi-mini-logo.jpg");
  }
  div { padding: 80px; margin: 30px; border-radius: 4%; }
  .in { background: rgba(0,40,0,0.4); }
</style>
</head>
<body>
  <div id="one">
    <div class="in"></div><div class="in"></div><div class="in"></div>
    <div class="in"></div><div class="in"></div>
  </div>
</body>
</html>

Kết quả

Ban đầu:

Background Attachment (Đính kèm nền) trong CSS

Khi cuộn (scroll) - hình ảnh nền KHÔNG di chuyển:

Background Attachment (Đính kèm nền) trong CSS

So sánh 3 giá trị:

Giá trịHành vi khi scrollĐối tượng tham chiếu
scroll (mặc định)Cuộn cùng với elementElement chứa background
fixedCố định, KHÔNG cuộnViewport (cửa sổ trình duyệt)
localCuộn cùng với nội dung elementNội dung của element (scroll container)

Lưu ý:

  • fixed không hoạt động tốt trên mobile (iOS Safari cũ, một số Android) - thường fallback thành scroll
  • local hữu ích khi element có overflow: auto/scroll (scrollable container)
  • Parallax effect thường dùng background-attachment: fixed
  • Performance: fixed có thể gây jank khi scroll, cân nhắc dùng transform: translate3d thay thế