How to Set Background Image in CSS: Simple Guide
To set a background image in CSS, use the
background-image property with the url() function specifying the image path. For example, background-image: url('image.jpg'); applies the image as the background of an element.Syntax
The background-image property sets an image as the background of an element. Use the url() function to specify the image file path or URL.
- background-image: CSS property to set the background image.
- url('path'): Function that points to the image location.
css
selector {
background-image: url('path-to-image.jpg');
}Example
This example shows how to set a background image on the whole page using the body selector. The image covers the entire background without repeating.
css
body {
background-image: url('https://via.placeholder.com/600x400');
background-repeat: no-repeat;
background-size: cover;
background-position: center;
height: 100vh;
margin: 0;
}Output
A webpage with a full-screen background image centered and covering the entire visible area without repeating.
Common Pitfalls
Common mistakes when setting background images include:
- Forgetting quotes around the URL or using incorrect path syntax.
- Not setting
background-repeat, causing the image to tile unexpectedly. - Not controlling
background-size, so the image may not fit well. - Using relative paths incorrectly, leading to broken images.
Always check the image path and use properties like background-repeat and background-size to control appearance.
css
/* Wrong way: missing quotes and no repeat control */ div { background-image: url(image.jpg); } /* Right way: quotes and no-repeat */ div { background-image: url('image.jpg'); background-repeat: no-repeat; background-size: contain; }
Quick Reference
| Property | Description | Example Value |
|---|---|---|
| background-image | Sets the background image | url('image.jpg') |
| background-repeat | Controls if image repeats | no-repeat, repeat, repeat-x |
| background-size | Controls image size | cover, contain, 100px 200px |
| background-position | Sets image position | center, top right, 50% 50% |
| background-attachment | Fixes image on scroll | fixed, scroll |
Key Takeaways
Use
background-image: url('path') to set a background image in CSS.Always check the image path and use quotes around the URL.
Control image repetition with
background-repeat to avoid tiling.Use
background-size to make the image fit the element nicely.Combine properties like
background-position and background-attachment for better control.