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

Đặt Background Position (Vị trí nền) trong CSS

Thuộc tính CSS background-position được dùng để đặt vị trí ban đầu cho hình ảnh nền (background image) tương đối với gốc tọa độ (origin).

Cú pháp

Selector {
  background-position: /*value*/
}

Ví dụ 1: Multiple backgrounds với position khác nhau

<!DOCTYPE html>
<html>
<head>
<style>
  div {
    margin: 30px; padding: 100px;
    background-image: url("https://www.tutorialspoint.com/images/C-programming.png"),
                      url("https://www.tutorialspoint.com/images/Swift.png"),
                      url("https://www.tutorialspoint.com/images/xamarian.png");
    background-repeat: no-repeat;
    background-position: 15% 20%, top, right;
    border: 1px solid;
  }
</style>
</head>
<body>
  <div> </div>
</body>
</html>

Kết quả

Đặt Background Position (Vị trí nền) trong CSS

Ví dụ 2: Background position với từ khóa và giá trị tuyệt đối

<!DOCTYPE html>
<html>
<head>
<style>
  p {
    margin: 20px; padding: 80px;
    background-image: url("https://www.tutorialspoint.com/images/dbms.png"),
                      url("https://www.tutorialspoint.com/images/Operating-System.png");
    background-repeat: no-repeat;
    background-position: 0 0, bottom right;
    background-color: lemonchiffon;
  }
</style>
</head>
<body>
  <p>This is demo paragraph. This is demo paragraph. This is demo paragraph. This is demo paragraph. This is demo paragraph. This is demo paragraph. This is demo paragraph. This is demo paragraph. This is demo paragraph. This is demo paragraph. This is demo paragraph. This is demo paragraph. This is demo paragraph. This is demo paragraph. </p>
</body>
</html>

Kết quả

Đặt Background Position (Vị trí nền) trong CSS

Các giá trị background-position:

LoạiGiá trịMô tả
Keywordsleft top / left center / left bottomGóc trái / giữa trái / dưới trái
center top / center / center bottomGiữa trên / chính giữa / giữa dưới
right top / right center / right bottomGóc phải / giữa phải / dưới phải
Length/PercentageX Y (px, em, %, v.v.)Tọa độ từ góc trên trái (0 0)
X% Y%Phần trăm của (container - image)
Mixleft 20px, bottom 10pxOffset từ cạnh (CSS3)

Lưu ý:

  • Mặc định: 0 0 (top left)
  • Nếu chỉ cho 1 giá trị: giá trị 2 mặc định là center
  • Với multiple backgrounds: cách nhau bởi dấu phẩy, tương ứng từng layer
  • background-origin ảnh hưởng đến điểm gốc tính toán position