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

Đặt Background Image (Hình ảnh nền) với CSS

Thuộc tính CSS background-image được dùng để đặt một hình ảnh làm nền cho phần tử được chọn.

Cú pháp

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

Ví dụ 1: Background image với cover và content-box

<!DOCTYPE html>
<html>
<head>
<style>
  #demo {
    margin: 24px; box-shadow: 0 0 5px black; padding: 20px;
    background-image: url("https://www.tutorialspoint.com/servlets/images/servlets.jpg");
    background-origin: content-box; background-repeat: no-repeat; background-size: cover;
    text-shadow: 0 1px white; font-size: 1.4em;
  }
  p { box-shadow: 0 0 5px grey; }
</style>
</head>
<body>
  <h2>Learn Python Blockchain</h2>
  <div id="demo">
    <p>Servlets are programs that run on a Web or Application server and act as a middle layer between a requests coming from a Web browser or other HTTP client and databases or applications on the HTTP server. Using Servlets, you can collect input from users through web page forms, present records from a database or another source, and create web pages dynamically.</p>
  </div>
</body>
</html>

Kết quả

Đặt Background Image (Hình ảnh nền) với CSS

Ví dụ 2: Multiple background images

<!DOCTYPE html>
<html>
<head>
<style>
  div { height: 150px; width: 150px; background-image: url("https://www.tutorialspoint.com/spring/images/spring-mini-logo.jpg"); border: 2px solid brown; }
  div > div { height: 80px; width: 80px; margin-right: 50px; background-image: url("https://www.tutorialspoint.com/images/hibernate.png"); }
  h1 { background-image: url("https://www.tutorialspoint.com/hibernate/images/hibernate-patterns.jpg"); background-repeat: no-repeat; color: black; }
</style>
</head>
<body>
  <h1>Demo</h1>
  <div> <div></div> </div>
</body>
</html>

Kết quả

Đặt Background Image (Hình ảnh nền) với CSS

Các thuộc tính liên quan quan trọng:

  • background-repeat: repeat (mặc định), no-repeat, repeat-x, repeat-y, space, round
  • background-position: top left, center, bottom right, 50% 50%, 10px 20px
  • background-size: auto (mặc định), cover, contain, 100px 50px, 50%
  • background-origin: padding-box (mặc định), border-box, content-box
  • background-clip: border-box (mặc định), padding-box, content-box, text
  • background-attachment: scroll (mặc định), fixed, local

Multiple backgrounds (CSS3):

background-image: url("img1.png"), url("img2.jpg"), linear-gradient(45deg, red, blue);

Layer đầu tiên nằm trên cùng. Mỗi layer có thể có repeat, position, size riêng biệt.

Gradient cũng là background-image: linear-gradient(), radial-gradient(), conic-gradient(), repeating-* variants.