Background images are set using CSS, not the <img> tag. You can apply them to any HTML element using the background-image property.
Use the CSS background-image property with url():
<style>
body {
background-image: url('background.jpg');
}
</style>
<!-- Or on a specific div -->
<div style="
background-image: url('bg.jpg');
height: 300px;">
Content here
</div>
By default, background images repeat both horizontally and vertically to fill the element. Control this with background-repeat:
/* Repeat in both directions (default) */
background-repeat: repeat;
/* Repeat only horizontally */
background-repeat: repeat-x;
/* Repeat only vertically */
background-repeat: repeat-y;
/* Do not repeat — show image once */
background-repeat: no-repeat;
| Value | Description |
|---|---|
repeat | Tiles the image in both directions (default) |
repeat-x | Tiles horizontally only |
repeat-y | Tiles vertically only |
no-repeat | Shows the image only once |
space | Distributes images evenly with spacing |
round | Scales images to fill without gaps |
When using no-repeat, control where the image appears:
background-repeat: no-repeat;
background-position: center center;
/* Other values */
background-position: top left;
background-position: bottom right;
background-position: 50% 50%;
background-position: 20px 40px;
Control how large the background image is rendered:
/* Scale to cover entire element (crop if needed) */
background-size: cover;
/* Scale to fit entirely (may leave gaps) */
background-size: contain;
/* Exact size */
background-size: 300px 200px;
/* Width only (height auto) */
background-size: 100%;
| Value | Description |
|---|---|
cover | Scales image to cover entire element — most popular choice |
contain | Scales image to fit inside — no cropping |
auto | Uses the image's original size (default) |
100% 100% | Stretches to fill exactly — may distort |
A common pattern for a full-page background:
body {
background-image: url('hero.jpg');
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center;
background-size: cover;
}
background-attachment: fixed to create a parallax effect — the background stays fixed while the content scrolls over it.
| Value | Description |
|---|---|
scroll | Background scrolls with the content (default) |
fixed | Background stays fixed — parallax effect |
local | Background scrolls with the element's content |
Combine all background properties into one line:
/* Shorthand format */
background: url('image.jpg')
no-repeat
center center / cover
fixed;
<div style="
background-image: url('pattern.png');
background-repeat: repeat;
padding: 40px;
color: white;">
Content on a patterned background.
</div>
text-shadow when needed.