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
| Property | Description |
|---|---|
background-image | Sets the background image |
background-repeat | Repeats or stops repeating the image |
background-size | Controls image size (cover, contain, or dimensions) |
background-position | Sets the image position (e.g., center, top, left) |
background-attachment | Makes 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
Post a Comment