learn2kode.in

CSS Backgrounds

CSS backgrounds allow you to style the behind-area of any HTML element. You can add solid colors, images, gradients, patterns, or even create layered backgrounds. Background properties help enhance design, readability, and the overall visual appeal of your website.

1. Background Color

The background-color property sets a solid color behind an element.

box {
  background-color: lightblue;
}

You can use:

2. Background Image

You can add an image behind an element using:

box {
  background-image: url("image.jpg");
}

This image can be repeated, positioned, or sized based on your needs.

3. Background Repeat

Controls whether the image repeats:

Example

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

4. Background Position

Used to control image placement:

box {
  background-position: center top;
}

Common values:

5. Background Size

Controls the display size of background images.

Values

Example

box {
  background-size: cover;
}

6. Background Attachment

Defines scrolling behavior:

box {
  background-attachment: fixed;
}

7. Background Shorthand

You can combine all background properties:

box {
  background: url("bg.jpg") no-repeat center/cover fixed;
}

Order doesn’t have to be exact, but this format is commonly used.

8. Multiple Backgrounds

CSS supports layered backgrounds:

box {
  background:
    url("overlay.png") no-repeat center,
    url("main-bg.jpg") center/cover;
}