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

Thiết lập vị trí nền (Background Position) bằng CSS

Vị trí nền (background-position) thiết lập vị trí bắt đầu của hình ảnh nền.

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ả

Thiết lập vị trí nền (Background Position) bằng CSS

Ví dụ 2: 50% 50% (giữa)

<!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: 50% 50%;
}
</style>
</head>
<body>
<h1>Chi tiết</h1>
<p>Trung tâm thi gần trường ABC College.</p>
<p>Kỳ thi bắt đầu lúc 9AM.</p>
</body>
</html>

Kết quả

Thiết lập vị trí nền (Background Position) bằng CSS

Giá trị thường dùng:

Từ khóaTương đương %
left top0% 0%
center top50% 0%
right top100% 0%
left center0% 50%
center center50% 50%
right center100% 50%
left bottom0% 100%
center bottom50% 100%
right bottom100% 100%

Có thể dùng 1 giá trị (giá trị 2 mặc định center), hoặc 2 giá trị (x, y).