Background image
Learn background-image and related properties.
What is background-image?
background-image puts an image on an element's surface. The most common form is the url() function: background-image: url("/images/hero.jpg").
Quoting the file path is a good habit, and required for paths with spaces. By default the image starts at the surface's top-left corner and repeats horizontally and vertically until it fills the box.
background-repeat
background-repeat controls how the image tiles. The default is repeat; the image repeats both horizontally and vertically.
Common values: no-repeat shows the image once; repeat-x repeats only horizontally; repeat-y only vertically. You usually want no-repeat for a badge icon and repeat for a texture.
background-position
background-position sets where the image sits inside the surface. In its simplest form it takes two keywords, like center top or left center.
You can also use percentages or pixels: 50% 0 places the image centered horizontally and at the top. It is common in a hero section to align the image's focus point to the top or the center.
Exercise Add an image to the .hero section
Add a .hero class selector. Set its background-image property to url("/images/hero.jpg"), its background-repeat property to no-repeat, and its background-position property to center top.
Show example solution
/* add an image to the .hero section */
.hero {
background-image: url("/images/hero.jpg");
background-repeat: no-repeat;
background-position: center top;
}
Test yourself
-
Which is a valid background-image value?
- url("/images/hero.jpg")
- src="/images/hero.jpg"
- img("/images/hero.jpg")
- /images/hero.jpg
Show answer
url("/images/hero.jpg") — Correct. The url() function takes the image path in quotes; background-image expects it.
-
Write the repeat value so the icon shows once
.icon { background-image: url("/images/check.png"); background-repeat: ____; }Show answer
.icon { background-image: url("/images/check.png"); background-repeat: no-repeat; } -
Match each value to its meaning
- no-repeat
- Image shown once
- repeat-x
- Repeats only horizontally
- center top
- Aligned to top center
- url("/x.png")
- Image path is loaded