CSS Backgrounds

Design beautiful sections using colors, images, gradients, and patterns.

What are CSS Backgrounds?

CSS Backgrounds allow you to control the background of HTML elements using colors, images, or gradients.

  • Add visual depth to sections
  • Improve readability
  • Create modern UI layouts
  • Enhance user experience

Real-Life Example: Like painting a wall with a color or wallpaper.

background-color

Sets the background color of an element.

Background Color Example


.box {
    background-color: #2563eb;
    color: white;
    padding: 20px;
}

                

background-image

Adds an image as the background.

Background Image Example


.hero {
    background-image: url("banner.jpg");
    height: 300px;
}

                

background-repeat

Controls whether the background image repeats.

  • repeat (default)
  • no-repeat
  • repeat-x
  • repeat-y

.section {
    background-image: url("pattern.png");
    background-repeat: no-repeat;
}

                

background-position & background-size

Control where the image appears and how large it is.

Cover Background Example


.banner {
    background-image: url("hero.jpg");
    background-position: center;
    background-size: cover;
    height: 400px;
}

                

background-attachment

Controls scrolling behavior of the background image.

  • scroll (default)
  • fixed (parallax effect)

.parallax {
    background-image: url("bg.jpg");
    background-attachment: fixed;
}

                

Background Shorthand

Combine multiple background properties into one line.

Shorthand Example


.card {
    background: url("card.png") no-repeat center / cover;
}

                

Best Practices for CSS Backgrounds

  • Use optimized images
  • Prefer gradients for performance
  • Use contrast for readability
  • Avoid text over busy images

Pro Tip: A clean background makes your content shine.