CSS Background – thuộc tính background trong CSS – VietTuts

Chương này hướng dẫn bạn làm thế nào để thiết lập nền của các phần tử HTML khác nhau. Bạn có thể thiết lập các thuộc tính nền sau của một phần tử:

Sau đây là ví dụ thể hiện cách thiết lập màu nền cho một phần tử.

Nó sẽ tạo ra kết quả sau:

Chúng ta có thể thiết lập hình nền bằng cách gọi các hình ảnh được lưu trữ cục bộ như thể hiện dưới đây

Nó sẽ tạo ra kết quả sau:

Theo mặc định, thuộc tính background-repeat lặp lại hình nền theo chiều ngang và chiều dọc. Một số hình ảnh được lặp lại chỉ theo chiều ngang hoặc chiều dọc.

Dưới đây là ví dụ về lặp hình nền theo chiều ngang: background-repeat: repeat-x;

Nó sẽ tạo ra kết quả sau:

Ví dụ sau minh họa cách lặp lại hình nền theo chiều dọc: background-repeat: repeat-y;

Nó sẽ tạo ra kết quả sau:

Ví dụ sau minh chứng cách lặp lại hình nền theo mặc định.

Nó sẽ tạo ra kết quả sau:

Thuộc tính background-position được sử dụng để xác định vị trí ban đầu của hình nền. Theo mặc định, hình nền được đặt ở phía trên bên trái của trang web.

Thuộc tính background-position có những giá trị sau:

Dưới đây là ví dụ về vị trí của hình nền trong CSS.

Nó sẽ tạo ra kết quả sau:

Tệp đính kèm nền xác định liệu một hình nền được cố định hay cuộn với phần còn lại của trang.

Ví dụ dưới đây thể hiện cách thiết lập hình nền cố định.


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
body {
  background: white url('bg2.gif');
  background-repeat: no-repeat;
  background-attachment: fixed;
  margin-left: 200px;
}
</style>
</head>
<body>
  <p>This is a fixed background-image. Scroll down the page.</p>
  <p>This is a fixed background-image. Scroll down the page.</p>
  <p>This is a fixed background-image. Scroll down the page.</p>
  <p>This is a fixed background-image. Scroll down the page.</p>
  <p>This is a fixed background-image. Scroll down the page.</p>
  <p>This is a fixed background-image. Scroll down the page.</p>
  <p>This is a fixed background-image. Scroll down the page.</p>
  <p>This is a fixed background-image. Scroll down the page.</p>
  <p>This is a fixed background-image. Scroll down the page.</p>
  <p>This is a fixed background-image. Scroll down the page.</p>
  <p>This is a fixed background-image. Scroll down the page.</p>
  <p>This is a fixed background-image. Scroll down the page.</p>
  <p>This is a fixed background-image. Scroll down the page.</p>
  <p>This is a fixed background-image. Scroll down the page.</p>
  <p>This is a fixed background-image. Scroll down the page.</p>
  <p>If you do not see any scrollbars, Resize the browser window.</p>
</body>
</html>