D DevBrainBox

CSS Background

CSS

CSS Backgrounds

The CSS background properties are used to style the background of elements like color, images, repeat behavior, position, and size.

1. background-color

  • Sets the background color of an element.
div {
  background-color: lightblue;
}

2. background-image

  • Sets an image as the background.
div {
  background-image: url('image.jpg');
}

3. background-repeat

  • Controls if/how the background image repeats.
div {
  background-repeat: repeat;       /* default */
  background-repeat: no-repeat;    /* stops repeating */
  background-repeat: repeat-x;     /* repeats horizontally only */
  background-repeat: repeat-y;     /* repeats vertically only */
}

4. background-position

  • Sets the starting position of the background image.
div {
  bbackground-position: center;       /* center the image */
  background-position: top right;    /* align to top-right */
  background-position: 50% 50%;      /* center in % */
}

5. background-size

  • Controls the size of the background image.
div {
  background-size: cover;     /* fills container, may crop */
  background-size: contain;   /* fits without cropping */
  background-size: 100px 200px;  /* fixed size */
}

6. background-attachment

  • Specifies whether the background scrolls with the page or stays fixed.
div {
  background-attachment: scroll;  /* default */
  background-attachment: fixed;   /* background stays in place */
}

7. Background (Shorthand)

  • You can combine all background properties into a single line:
div {
  background: url('image.jpg') no-repeat center center / cover lightgray;
}

This includes:

  • image
  • repeat
  • position
  • size (after /)
  • background color

On this page