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

Tạo kiểu nền (Background) cho phần tử bằng CSS

Để tạo kiểu nền cho phần tử, bạn có thể thiết lập hình ảnh nền, vị trí nền. Cùng với đó, thiết lập lặp nền để lặp hình ảnh ngang hoặc dọc.

background-position

Vị trí nền thiết lập vị trí bắt đầu của hình ảnh nền. Sử dụng thuộc tính background-position.

Ví dụ 1: left center

<!DOCTYPE html>
<html>
<head>
<style>
body {
  background-image: url("https://www.tutorialspoint.com/images/Swift.png");
  background-repeat: no-repeat;
  background-attachment: fixed;
  color: blue;
  background-position: left center;
}
.demo { text-decoration: overline underline; }
</style>
</head>
<body>
<h1>Chi tiết</h1>
<p class="demo">Trung tâm thi gần trường ABC College.</p>
<p class="demo2">Kỳ thi bắt đầu lúc 9AM.</p>
</body>
</html>

Kết quả

Tạo kiểu nền (Background) cho phần tử bằng CSS

background-repeat

Lặp nền trong CSS thiết lập cách hình ảnh nền lặp lại. Sử dụng background-repeat.

background-repeat: repeat | repeat-x | repeat-y | no-repeat | initial | inherit;

Ví dụ 2: repeat-x

<!DOCTYPE html>
<html>
<head>
<style>
body {
  background-image: url("https://www.tutorialspoint.com/images/Swift.png");
  background-repeat: repeat-x;
  background-color: blue;
  color: white;
}
.demo { text-decoration: overline underline; }
</style>
</head>
<body>
<h1>Chi tiết</h1>
<p class="demo">Trung tâm thi gần trường ABC College.</p>
<p class="demo2">Kỳ thi bắt đầu lúc 9AM.</p>
</body>
</html>

Kết quả

Tạo kiểu nền (Background) cho phần tử bằng CSS

Tóm tắt:

  • background-position: left/center/right top/center/bottom hoặc % hoặc px
  • background-repeat: repeat (mặc định), repeat-x, repeat-y, no-repeat, space, round
  • background-attachment: fixed tạo hiệu ứng parallax
  • Shorthand: background: url(...) no-repeat fixed left center;