iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

CSS Backgrounds

CSS backgrounds let you add color, images, gradients, and patterns behind any element. Six longhand properties combine into one shorthand.

Background properties

PropertyPurposeExample
background-colorSolid colour behind the element.#04AA6D
background-imageA URL, gradient, or multiple layered images.url('hero.jpg')
background-repeatWhether/how the image tiles.no-repeat
background-positionWhere the image starts.center top
background-sizeHow the image is scaled.cover, contain
background-attachmentWhether the image scrolls with the page.fixed

cover vs contain

background-size: cover fills the box, may crop the image background-size: contain fits inside the box, may leave gaps
Fig 1. cover fills, contain fits. Pick based on whether cropping is acceptable.

The shorthand

background shorthand
background: #04AA6D url('hero.jpg') no-repeat center/cover fixed;
/*           color    image           repeat    pos/size scroll */
Tip: You can stack multiple images by separating them with commas — earlier images sit on top. Use this for gradient overlays on photographs.

Example

Example
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Verdana, sans-serif; }
.box { background: #04AA6D; color: #fff; padding: 20px; border-radius: 6px; }
</style>
</head>
<body>

<h1>CSS Backgrounds</h1>
<div class="box">Edit the CSS on the left, then click Run &raquo;</div>

</body>
</html>
Try it Yourself »

Exercise

Set the background image without tiling it.

body { background-image: url('bg.png'); background-repeat: ; }

Test yourself

Q1. Which property sets the background image?
Q2. What does `background-repeat: no-repeat` do?
Q3. Which shorthand sets background in one declaration?

Discussion

Loading…