Episode 43 of 53
CSS Backgrounds
Learn background-color, background-image, background-size, and positioning.
CSS provides powerful tools for adding and controlling backgrounds on elements.
Background Color
.box { background-color: #3498db; }
.subtle { background-color: rgba(0, 0, 0, 0.05); }
Background Image
.hero {
background-image: url('hero.jpg');
background-size: cover;
background-position: center;
background-repeat: no-repeat;
height: 400px;
}
Background Size
cover— scales image to fill element (may crop)contain— scales image to fit (may leave gaps)auto— original size- Specific values:
200px 100pxor50% auto
Background Position
.hero {
background-position: center center;
background-position: top right;
background-position: 50% 30%;
}
Background Repeat
/* Pattern tile */
.pattern {
background-image: url('pattern.png');
background-repeat: repeat; /* Default: tiles both ways */
}
/* Horizontal only */
.stripe { background-repeat: repeat-x; }
/* No repeat */
.photo { background-repeat: no-repeat; }
Background Attachment
/* Parallax-like fixed background */
.parallax {
background-image: url('bg.jpg');
background-attachment: fixed;
background-size: cover;
}