CSS BACKGROUND IMAGE

A background image in CSS is added using the background-image property.

Basic Syntax

selector {
  background-image: url("image.jpg");
}

Example 1: Background Image

<!DOCTYPE html>
<html>
<head>
<style>
body {
  background-image: url("background.jpg");
}
</style>
</head>
<body>
  <h1>Welcome</h1>
</body>
</html>

Example 2: No Repeat

body {
  background-image: url("background.jpg");
  background-repeat: no-repeat;
}

Example 3: Full-Screen Background

body {
  background-image: url("background.jpg");
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
  background-attachment: fixed;
}

Example 4: Image Covering a <div>

.box {
  width: 400px;
  height: 300px;
  background-image: url("nature.jpg");
  background-size: cover;
  background-position: center;
}

Common Background Image Properties

PropertyDescription
background-imageSets the background image
background-repeatRepeats or stops repeating the image
background-sizeControls image size (cover, contain, or dimensions)
background-positionSets the image position (e.g., center, top, left)
background-attachmentMakes the background scroll or stay fixed

Shorthand

body {
  background: url("background.jpg") no-repeat center center / cover;
}

This shorthand sets:

  • Image: background.jpg
  • Repeat: no-repeat
  • Position: center center
  • Size: cover

This is the most common way to create a responsive full-page background image.

Comments

Popular posts from this blog

HTML | HTML INTRODUCTION

CSS GROUPING SELECTORS

HTML LISTS