0
0
CSSmarkup~5 mins

Background image in CSS

Choose your learning style9 modes available
Introduction
A background image adds a picture behind the content of a webpage to make it look nicer and more interesting.
You want to add a photo behind text on a webpage.
You want to decorate a section with a pattern or texture.
You want to create a full-page image background for a landing page.
You want to add a logo or watermark behind content.
You want to make a button or card more attractive with an image.
Syntax
CSS
selector {
  background-image: url('path/to/image.jpg');
}
Use quotes around the URL path inside url().
The image path can be relative or absolute.
Examples
Sets a background image for the whole webpage.
CSS
body {
  background-image: url('background.jpg');
}
Adds a background image to the header and stops it from repeating.
CSS
.header {
  background-image: url('header-pattern.png');
  background-repeat: no-repeat;
}
Makes the background image cover the entire card area.
CSS
.card {
  background-image: url('card-bg.svg');
  background-size: cover;
}
Sample Program
This webpage shows a full-screen background image behind centered white text with a shadow for readability.
CSS
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Background Image Example</title>
  <style>
    body {
      margin: 0;
      font-family: Arial, sans-serif;
      background-image: url('https://images.unsplash.com/photo-1506744038136-46273834b3fb?auto=format&fit=crop&w=800&q=80');
      background-size: cover;
      background-position: center;
      background-repeat: no-repeat;
      color: white;
      height: 100vh;
      display: flex;
      justify-content: center;
      align-items: center;
      text-shadow: 0 0 5px black;
    }
    h1 {
      font-size: 3rem;
    }
  </style>
</head>
<body>
  <h1>Welcome to My Website</h1>
</body>
</html>
OutputSuccess
Important Notes
Use background-size: cover to make the image fill the area nicely without stretching.
Add background-position: center to keep the important part of the image visible.
Use background-repeat: no-repeat to avoid the image repeating if it is smaller than the area.
Summary
Background images add pictures behind webpage content to improve look and feel.
Use the CSS property background-image with url('image-path').
Combine with background-size, background-position, and background-repeat for best results.