Thuộc tính background là shorthand mạnh mẽ, cho phép đặt cùng lúc tới 8 thuộc tính nền: color, image, repeat, attachment, position, size, origin, clip.
Cú pháp
object.style.background = "color image repeat attachment position size origin clip|initial|inherit"
Các thành phần
| Thứ tự | Thuộc tính | Mô tả |
|---|---|---|
| 1 | color | Màu nền. |
| 2 | image | Hình nền (url). |
| 3 | repeat | Chế độ lặp. |
| 4 | attachment | scroll/fixed/local. |
| 5 | position | Vị trí khởi đầu. |
| 6 | size | Kích thước (cover, contain...). |
| 7 | origin | Vùng gốc (padding-box...). |
| 8 | clip | Vùng vẽ (border-box...). |
Ví dụ
Thay đổi hình nền div (chỉ demo thay image):
<!DOCTYPE html> <html> <head> <style>
#PIC {
width: 250px;
height: 150px;
border: solid 3px black;
font-weight: 100;
text-align: center;
color: white;
font-size: 40px;
background: url("https://www.tutorialspoint.com/python/images/python-mini.jpg") no-repeat fixed 2% 8%;
}
</style>
<script>
function changeBackground(){
document.getElementById("PIC").style.backgroundImage = "url(https://www.tutorialspoint.com/csharp/images/csharp-mini-logo.jpg)";
document.getElementById("Sample").innerHTML = "URL hình nền đã thay đổi";
}
</script> </head>
<body>
<h2>Học tập vui vẻ</h2>
<div id="PIC">Tutorial</div>
<p>Nhấn nút để đổi hình nền</p>
<button onclick="changeBackground()">THAY ĐỔI BACKGROUND</button>
<p id="Sample"></p>
</body> </html>
Kết quả
Hình nền ban đầu (Python logo):

Sau khi nhấn nút (C# logo):
