Day 2 - Backgrounds

The background properties allow you to define the background effects for elements.


1. Background Color

Sets the background color of an element.

Code:

/* CSS */
.bg-red {
    background-color: red;
}

.bg-blue {
    background-color: blue;
}

Output:

Red
Blue

2. Background Gradients

Gradients allow smooth transitions between two or more colors.

Code:

/* CSS */
/* Linear Gradient: Goes in a straight line */
.grad-linear {
    background-image: linear-gradient(to right, red, yellow);
}

/* Radial Gradient: Starts from center circles out */
.grad-radial {
    background-image: radial-gradient(circle, red, yellow, green);
}

Output:

Linear Gradient
Radial Gradient

3. Background Image & Size

Sets an image as the background. background-size controls scaling.

Code:

/* CSS */
/* cover: Crop image to fill the entire box */
.bg-img-cover {
    background-image:  url('./img/bg-beach.jpg');
    background-size:  cover;
    background-position:  center;
}

/* contain: Scale image to be  fully visible */
.bg-img-contain {
    background-image:  url('./img/bg-beach.jpg');
    background-size:  contain;
    background-repeat:  no-repeat;
}

Output:

"cover"
"contain"

3.5. Object Fit (For Img Tags)

While background-size works on backgrounds, object-fit controls how <img> tags scale inside their bounds.

Note: The position property (static/relative/absolute/fixed/sticky) controls element placement. Covered in detail later.

Code:

/* CSS */
.img-container {
    position:  relative;
}

.obj-fit-cover {
    width:  100%;
    height:  100%;
    object-fit:  cover;
    position:  absolute;
}
            
.obj-fit-contain {
    width:  100%;
    height:  100%;
    object-fit:  contain;
    position:  absolute;
}

Output:

"cover"

Beach

"contain"

Beach

4. Background Position

Specifies the starting position of a background image.

Code:

/* CSS */
.bg-pos-center {
    background-position:  center;
}
            
.bg-pos-br {
    background-position:  bottom right;
}

Output:

Center
Bottom Right

5. Background Repeat

By default, background images repeat both horizontally and vertically.

Code:

/* CSS */
.bg-repeat {
    background-repeat: repeat;
}  /* Default */

.bg-norepeat {
    background-repeat: no-repeat;
}

Output:

Repeat Pattern
No Repeat