19. Background Images and Tiling
CSS allows you to set an image as the background of any element using the background-image property.
Setting a Background Image
Use the url() function to point to the image file. Paths are relative to the CSS file location.
css .hero-section { /* Path assumes image is in the 'images' folder relative to the CSS file / background-image: url('../images/forest.jpg'); min-height: 400px; / Important: Background images need dimension to be seen */ color: white; }
Background Repeat (background-repeat)
By default, if an image is smaller than the element, the browser will tile (repeat) the image to fill the space. You usually need to control this behavior.
| Value | Description |
|---|---|
repeat (default) | Repeats horizontally and vertically. |
repeat-x | Repeats only horizontally. |
repeat-y | Repeats only vertically. |
no-repeat | Shows the image only once. |
css .texture { background-image: url('tile.png'); background-repeat: repeat-x; }
Background Position (background-position)
If you use no-repeat, you often want to position the image. This property takes two values: horizontal (left/center/right or a value) and vertical (top/center/bottom or a value).
css .centered-logo { background-image: url('logo.svg'); background-repeat: no-repeat; background-position: center center; /* Centers horizontally and vertically */ }