Upholstering the Web: CSS Backgrounds with Images
Master the essential CSS properties for creating beautiful, responsive, and visually engaging backgrounds on the web.
Welcome! Let's learn how to decorate our web elements using CSS background properties.
/* Our canvas is ready! */
Setting the Image
The background-image
property is your starting point. It sets one or more background images for an element. The value is typically the url()
function, pointing to the image file you want to use.
Controlling the Size
background-size
defines the size of the background images. Key values are cover
, which scales the image to fill the container (cropping if necessary), and contain
, which scales the image to fit inside the container without cropping.
Positioning with Precision
With background-position
, you can control where the background image is placed. You can use keywords like center
, top
, right
, or specific pixel/percentage values (e.g., 50% 50%
) for precise alignment.
The 'background' Shorthand
The shorthand background
property allows you to set all background properties in one declaration, making your code cleaner. For example: background: url('img.jpg') no-repeat center center / cover;
.
Practice Zone
Interactive Test 1: Drag & Drop
Arrastra en el orden correspondiente.
Arrastra las opciones:
Completa el código:
Interactive Test 2: Fill in the Blanks
Rellena los huecos en cada casilla.
.hero { background-image: ; background-size: ; background-position: ; }
Practice Example: Code Editor
Set a background image from `url("https://via.placeholder.com/400")`, prevent it from repeating, center it, and make it cover the entire element.
Advanced Background Techniques
Beyond the basics, CSS backgrounds offer powerful features for creating rich, dynamic designs. Let's explore some practical examples with live previews.
1. Creating a Parallax Effect with `background-attachment`
By setting background-attachment: fixed;
, the background image stays fixed within the viewport instead of scrolling with its container. This creates a simple but effective parallax scrolling effect.
.parallax-section {
background-image: url(...);
background-size: cover;
background-attachment: fixed;
}
Scroll me!
2. Layering Multiple Backgrounds
You can apply multiple background images to a single element by comma-separating the values. The first image listed is the topmost layer. Each layer can have its own position, size, and repeat properties.
.layered-bg {
background-image:
url('foreground.svg'),
url('background.jpg');
background-position: center, center;
background-size: 50px, cover;
background-repeat: no-repeat, no-repeat;
}
Practical Takeaway: Backgrounds are not just static decoration. By combining properties like `background-attachment` and layering multiple images, you can create depth and interactivity that significantly enhance the user experience.