← Back to Index

CSS Backgrounds Tutorial

Understanding CSS Backgrounds

CSS backgrounds are fundamental to web design, providing various ways to enhance the visual presentation of elements. They can be used to create depth, establish visual hierarchy, and improve the overall user experience.

Key Concepts:

  • Backgrounds can be layered using multiple background images
  • The background shorthand property combines multiple background properties
  • Background properties affect the painting area behind an element's content, padding, and border
  • Background images are painted in layers, with the first declared image being closest to the viewer

1. Background Color

The background-color property supports various color formats including hexadecimal, RGB, RGBA, HSL, and color keywords.


background-color: #ff0000; /* Hexadecimal */
background-color: rgb(255, 0, 0); /* RGB */
background-color: rgba(255, 0, 0, 0.5); /* RGBA with opacity */
background-color: hsl(0, 100%, 50%); /* HSL */
background-color: red; /* Color keyword */
            

2. Background Image

Background images can be used to add texture, patterns, or visual content to elements.


background-image: url('image.jpg');
background-image: linear-gradient(to right, red, blue);
background-image: radial-gradient(circle, red, blue);
background-image: url('image1.jpg'), url('image2.jpg'); /* Multiple backgrounds */
            

3. Background Repeat

Controls how background images repeat when they don't cover the entire container.


background-repeat: repeat; /* Default */
background-repeat: no-repeat;
background-repeat: repeat-x;
background-repeat: repeat-y;
background-repeat: space;
background-repeat: round;
            

4. Background Size

Controls how background images are sized within their container.


background-size: cover; /* Scales image to cover container */
background-size: contain; /* Scales image to fit within container */
background-size: 100% 100%; /* Stretches image */
background-size: auto 50%; /* Maintains aspect ratio */
            

5. Background Position

Determines where the background image is placed within its container.


background-position: center center;
background-position: top left;
background-position: 50% 50%;
background-position: right 20px bottom 10px;
            

6. Background Attachment

Controls how the background image behaves when scrolling.


background-attachment: scroll; /* Scrolls with content */
background-attachment: fixed; /* Stays fixed relative to viewport */
background-attachment: local; /* Scrolls with element's contents */
            

Scroll to see the fixed background effect

7. Background Blend Mode

Controls how background layers blend with each other.


background-blend-mode: normal;
background-blend-mode: multiply;
background-blend-mode: screen;
background-blend-mode: overlay;
            

Best Practices