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:

Khi cuộn (scroll):

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:

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

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 element | Element chứa background |
fixed | Cố định, KHÔNG cuộn | Viewport (cửa sổ trình duyệt) |
local | Cuộn cùng với nội dung element | Nội dung của element (scroll container) |
Lưu ý:
fixedkhông hoạt động tốt trên mobile (iOS Safari cũ, một số Android) - thường fallback thànhscrolllocalhữu ích khi element cóoverflow: auto/scroll(scrollable container)- Parallax effect thường dùng
background-attachment: fixed - Performance:
fixedcó thể gây jank khi scroll, cân nhắc dùngtransform: translate3dthay thế