Skip to content

CSS Backgrounds

Overview

Background properties control the background of elements, including colors, images, and gradients.

Background Color

css
.element {
    background-color: #f0f0f0;
    background-color: rgb(240, 248, 255);
    background-color: rgba(240, 248, 255, 0.8);
    background-color: hsl(200, 100%, 97%);
    background-color: hsla(200, 100%, 97%, 0.8);
}

Background Image

css
.element {
    background-image: url('image.jpg');
    background-repeat: no-repeat;
    background-position: center center;
    background-size: cover;
}

/* Shorthand */
.element {
    background: url('image.jpg') no-repeat center center / cover;
}

Background Gradients

Linear Gradients

css
.linear-gradient {
    background: linear-gradient(45deg, #ff6b6b, #4ecdc4);
}

.linear-gradient-stops {
    background: linear-gradient(to right, #ff6b6b 0%, #4ecdc4 50%, #45b7d1 100%);
}

Radial Gradients

css
.radial-gradient {
    background: radial-gradient(circle, #ff6b6b, #4ecdc4);
}

.radial-gradient-position {
    background: radial-gradient(circle at top left, #ff6b6b, #4ecdc4);
}

Multiple Backgrounds

css
.multiple-backgrounds {
    background: 
        url('pattern.png') repeat,
        url('image.jpg') no-repeat center center / cover,
        linear-gradient(45deg, rgba(255, 255, 255, 0.1), rgba(0, 0, 0, 0.1));
}

Background Properties

Background Size

css
.cover-background {
    background-size: cover; /* Covers entire element */
}

.contain-background {
    background-size: contain; /* Fits entire image */
}

.specific-size {
    background-size: 300px 200px; /* Width height */
}

Background Position

css
.positioned-background {
    background-position: center center;
    background-position: 50% 50%;
    background-position: top right;
    background-position: 100px 50px;
}

Background Attachment

css
.fixed-background {
    background-attachment: fixed; /* Stays fixed when scrolling */
}

.scroll-background {
    background-attachment: scroll; /* Scrolls with content */
}

.local-background {
    background-attachment: local; /* Scrolls with element content */
}

Common Patterns

Hero Section

css
.hero {
    background: 
        linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)),
        url('hero-image.jpg') no-repeat center center / cover;
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    text-align: center;
}

Card Background

css
.card {
    background: white;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    border-radius: 8px;
}

Pattern Background

css
.pattern-background {
    background-color: #f8f9fa;
    background-image: 
        repeating-linear-gradient(45deg, transparent, transparent 10px, rgba(0, 0, 0, 0.1) 10px, rgba(0, 0, 0, 0.1) 20px);
}

Content is for learning and research only.