CSS Background - Everything You Need to Know
Complete guide to CSS background properties, from basic colors to advanced techniques with gradients and multiple backgrounds
Overview
Complete guide to CSS background properties, from basic colors to advanced techniques with gradients and multiple backgrounds
Reference Content
Basic Background Properties
.element {
/ Named colors /
background-color: red;/ Hex values /
background-color: #ff5733;
/ RGB/RGBA /
background-color: rgb(255, 87, 51);
background-color: rgba(255, 87, 51, 0.8);
/ HSL/HSLA /
background-color: hsl(9, 100%, 60%);
background-color: hsla(9, 100%, 60%, 0.8);
/ CSS Variables /
background-color: var(--primary-color);
}
Gradients
.element {
/ Basic gradient /
background: linear-gradient(to right, red, blue);/ With angle /
background: linear-gradient(45deg, red, blue);
/ Multiple color stops /
background: linear-gradient(to right, red 0%, yellow 50%, blue 100%);
/ Sharp transitions /
background: linear-gradient(to right, red 50%, blue 50%);
/ Repeating gradient /
background: repeating-linear-gradient(
45deg,
transparent,
transparent 10px,
#ccc 10px,
#ccc 20px
);
}
Advanced Patterns
.hero {
background:
linear-gradient(
to bottom,
rgba(0, 0, 0, 0.3),
rgba(0, 0, 0, 0.7)
),
url('hero-image.jpg');
background-size: cover;
background-position: center;
background-attachment: fixed;
height: 100vh;
}Performance Considerations
.optimized {
/ Use modern formats /
background-image:
url('image.webp'),
url('image.jpg'); / Fallback // Lazy loading for below-fold images /
content-visibility: auto;
/ Prevent repaints /
will-change: background-position;
}
Responsive Backgrounds
.responsive-bg {
/ Mobile /
background-image: url('mobile-bg.jpg');/ Tablet /
@media (min-width: 768px) {
background-image: url('tablet-bg.jpg');
}
/ Desktop /
@media (min-width: 1024px) {
background-image: url('desktop-bg.jpg');
}
}