CSS Background Image: Layering Pixels
A website without rich backgrounds is like a canvas without paint. Mastering the CSS `background-image` property (and its companions) is fundamental for creating immersive, modern web designs. Let's dig deep.
The Basics: The url() Function
To load an external image file, you pass a relative or absolute path into the url() function.
background-image: url('../images/hero.jpg');
Always ensure your image paths are correct relative to where your CSS file is located, not the HTML file (unless the styles are inline).
Controlling the Flow: Repeat, Size & Position
By default, the browser will tile an image if it's smaller than its container. We manipulate this using:
- background-repeat: Set to
no-repeatto stop tiling. You can also userepeat-x(horizontal only) orrepeat-y. - background-size: The powerhouse property.
coverensures the whole div is filled (cropping if needed), whilecontainensures the whole image is visible (leaving blank space if needed). - background-position: Aligns the image.
center centerperfectly centers it, but you can also use pixels or percentages (e.g.,top leftor50% 100%).
Gradients: Painting with Math
CSS Gradients are technically treated as background-image. Because the browser renders them programmatically, they are incredibly performant and sharp at any resolution.
linear-gradient(to bottom right, #ff0099, #00f0ff);
View Accessibility & Performance Tips+
Fallback Colors: Always provide a background-color fallback. If the user's connection is slow, or the image link breaks, the solid color will render first so your text remains readable.
Image Optimization: Don't load a 5MB background image. Compress your images and serve modern formats like WebP or AVIF whenever possible to ensure fast loading times.
❓ Frequently Asked Questions
¿Cuál es la diferencia entre background-size cover y contain?
cover: Escala la imagen para cubrir completamente el contenedor, recortándola si es necesario. Perfecto para imágenes hero o fondos que deben llenar todo el espacio sin dejar espacios vacíos.
contain: Escala la imagen manteniéndola completamente visible dentro del contenedor. Puede dejar espacios vacíos (generalmente rellenados con el background-color). Ideal cuando necesitas ver toda la imagen sin recortes.
/* Cover: rellena todo, puede recortar */ background-size: cover; /* Contain: muestra toda la imagen, puede dejar espacios */ background-size: contain;¿Cuándo debo usar cover y cuándo contain?
Usa cover cuando:
- Necesitas una imagen hero o banner de fondo
- El recorte de la imagen no afecta el contenido importante
- Quieres un diseño moderno y limpio sin espacios vacíos
Usa contain cuando:
- Es crítico que se vea toda la imagen sin recortes
- La imagen contiene elementos importantes en los bordes
- Trabajas con iconos o logos como fondos
¿Cómo centro correctamente una imagen de fondo?
Combina `background-size`, `background-position` y `background-repeat`:
.hero {background-image: url('image.jpg'); background-size: cover; background-position: center; background-repeat: no-repeat;}