HTML allows you to add background colors, images, and patterns to elements using CSS. Backgrounds make web pages more visually appealing and help highlight specific sections.
Use the background-color property to set the background color of any HTML element.
<body style="background-color: lightblue;">
<h2 style="background-color: yellow;">Highlighted Heading</h2>
<p style="background-color: lightgray;">This is a paragraph with a gray background.</p>
</body>
You can apply a background image using the background-image property.
<body style="background-image: url('background.jpg');">
<h2>Page with Background Image</h2>
</body>
Defines whether the background image should repeat.
| Value | Meaning |
|---|---|
repeat |
Repeats both vertically & horizontally |
repeat-x |
Repeats horizontally only |
repeat-y |
Repeats vertically only |
no-repeat |
No repetition |
<body style="background-image: url('bg.png'); background-repeat: no-repeat;">
</body>
Controls how the image fits the element.
| Value | Description |
|---|---|
auto |
Original image size |
cover |
Covers entire area (may crop) |
contain |
Fits inside area (may leave space) |
<body style="background-image: url('bg.jpg'); background-size: cover;">
</body>
Defines where the background image appears.
<body style="background-image: url('bg.jpg'); background-position: center;">
</body>
You can apply more than one background image.
<div style="
background-image: url('img1.png'), url('img2.png');
background-position: left top, right bottom;
background-repeat: no-repeat, no-repeat;
">
Multiple backgrounds applied
</div>
Combine all background properties into one line:
<body style="background: url('bg.jpg') no-repeat center/cover;">
</body>