SmartCodingTips

CSS Backgrounds

The CSS background properties let you add color, images, gradients, and patterns behind elements. This enhances the visual appeal and layout structure of a webpage.

1. Background Color

Set a background color using background-color:


.box {
    background-color: #f0f0f0;
}
            

2. Background Image

Use background-image to apply an image:


.hero {
    background-image: url('banner.jpg');
}
            

3. Background Repeat

Control whether the image repeats:


.hero {
    background-repeat: no-repeat;
}
            

4. Background Position

Position the background image inside the element:


.hero {
    background-position: center center;
}
            

5. Background Size

Control the scaling of the background image:


.hero {
    background-size: cover;
}
            
  • cover – fills the container, cropping if needed
  • contain – fits the image inside the container

6. Background Attachment

Set whether the background scrolls with the content or is fixed:


.hero {
    background-attachment: fixed;
}
            

7. Shorthand Background Property

Combine multiple background properties in one line:


.hero {
    background: url('bg.jpg') no-repeat center center / cover;
}
            

8. Multiple Backgrounds

You can layer several background images:


.layered {
    background: url('overlay.png'), url('main.jpg');
    background-repeat: no-repeat;
    background-position: top left, center center;
}
            

Conclusion

CSS backgrounds give you control over color, images, and visual texture. Combine properties like position, size, and repeat to create stunning web designs.