CSS Backgrounds: Painting the Canvas
The background of an element is the canvas upon which its content is drawn. Mastering CSS background properties lets you layer images, gradients, and colors to create deep, engaging interfaces.
The Base: Background Color
The simplest background is a solid color. You can set this using background-color. You can use keywords, hex codes, RGB, or HSL. Crucially, using rgba() or hsla() allows you to control the opacity of the background without affecting the text inside the element.
Visuals: Background Images & Gradients
Use background-image: url('...'); to load images. Interestingly, CSS gradients (like linear-gradient()) are also treated as background images, not colors! This means you can stack them.
By default, a background image will repeat on both the X and Y axes to fill the container. You can control this with background-repeat: no-repeat | repeat-x | repeat-y.
Control: Size and Position
Rarely does an image perfectly match the size of its container. This is where sizing comes in:
- cover: Scales the image as large as possible to fill the container, cropping parts if necessary. Ideal for hero sections.
- contain: Scales the image as large as possible without cropping. It ensures the whole image is visible, but might leave empty space.
- background-position: Aligns the image (e.g.,
center,top right, or specific pixel/percentage values).
Pro-Tip: The Background Shorthand+
Instead of writing 5 different properties, use the background shorthand. The order is generally:[color] [image] [repeat] [attachment] [position] / [size]
Example: background: #333 url('bg.png') no-repeat fixed center / cover;. Notice the slash (/) separating position and size!
❓ Preguntas Frecuentes
What's the difference between cover and contain?
Cover: Fills the entire container. If the image and container have different proportions (aspect ratio), the image will be cropped at the edges to avoid white space. This is ideal for banners.
Contain: Scales the image to be fully visible within the container without cropping. If the proportions don't match, you'll see empty space (horizontal or vertical bars) around the image.
How do I create a simple Parallax effect?
You can create a basic "Parallax" effect where the background image stays fixed while you scroll the page using thebackground-attachment property.
.parallax {background-image: url('photo.jpg'); background-attachment: fixed; /* This creates the effect */ background-position: center; background-size: cover;}How do I darken a background image so text is readable?
You can use CSS's ability to have multiple backgrounds. Place a semi-transparent gradient before the image (earlier layers render on top).
.hero {background: linear-gradient(rgba(0,0,0,0.6), rgba(0,0,0,0.6)), /* Dark overlay */ url('background.jpg') center / cover;}