Adding Background Images in CSS
Background images add a lot of visual interest to a website. Not only can we have a background image for the entire page, but each box (container) can have its own background image. Let's look at the key CSS properties, then some real examples.
The Core Property
The most important property for background images is background-image:
background-image: url(images/background.jpg);
The URL specifies the image location relative to the stylesheet.
Controlling Repeat
By default, a background image tiles in all directions. The background-repeat property controls this behavior:
background-repeat: repeat-x; /* horizontal only */
background-repeat: repeat-y; /* vertical only */
background-repeat: no-repeat; /* show once */
background-repeat: repeat; /* tile all directions (default) */
A Full-Page Background Example
Here is a real-world example using a background image on the body tag, repeated horizontally across the top of the page:
body {
background-color: #2f261f;
font-family: "Times New Roman", Times, serif;
background-image: url(images/bk_top.jpg);
background-repeat: repeat-x;
color: #fff;
font-size: 15px;
}
I'm also including a background-color. The image only covers the top portion of the page — the background-color fills the rest of the browser window. Keeping the solid color as a CSS property rather than extending the image keeps file size small.
Background Image Inside a Box
#infobox {
background-image: url(images/logo_top.jpg);
background-color: #FFC;
width: 350px;
padding: 80px 10px 10px 10px;
border: dotted #09F;
}
The image appears in the upper area of the box; the background-color fills the rest. Adding generous top padding pushes the text content below the image area.
Modern Background Control
Two additional properties give you full control for modern layouts:
background-size: cover; /* scale to fill container, may crop */
background-size: contain; /* scale to fit without cropping */
background-position: center; /* center the image */
For full-width hero images, background-size: cover combined with background-position: center is the standard approach today.