Css backgrounds

CSS backgrounds let you paint elements with colors, images, and gradients, and control how they position, scale, repeat, and attach to the page. Understanding each property and the shorthand helps you create polished, accessible interfaces that behave consistently across layouts.

Background color and background image

Background color

  • Purpose: Apply a solid color behind an element’s content and padding.
  • Accepted values: Named colors, hex, rgb(), rgba(), hsl(), hsla().

Code Block Loading...

Background image

  • Purpose: Use an image (or gradient) instead of a solid color.
  • Syntax: background-image: url("path/to/image.png"); or a gradient function.

Code Block Loading...

Tip: Always pair background images with suitable contrast and fallback colors where appropriate.

Background clip, origin, and positioning

Background clip

  • Purpose: Controls how far the background color/image extends.
  • Values:
    • border-box: Extends under border, padding, and content (default for painting area).
    • padding-box: Stops at the padding edge; the border won’t be painted underneath.
    • content-box: Stops at the content box; excludes padding and border.

Code Block Loading...

Background origin

  • Purpose: Sets the origin box for background-image positioning.
  • Values: padding-box (default), border-box, content-box.

Code Block Loading...

Background position

  • Purpose: Places the image within its box.
  • Values: Keywords (left, center, right, top, bottom), or lengths/percentages.

Code Block Loading...

Background repeat, attachment, and size

Background repeat

  • Purpose: Defines tiling behavior.
  • Values: repeat (default), repeat-x, repeat-y, no-repeat, space, round.

Code Block Loading...

Background attachment

  • Purpose: Controls whether the background scrolls with content or stays fixed in the viewport.
  • Values: scroll (default), fixed, local.

Code Block Loading...

Background size

  • Purpose: Scales the background image.
  • Values: auto (default), cover, contain, or explicit lengths.

Code Block Loading...

Background shorthand and fallbacks

Shorthand syntax

  • Purpose: Combine multiple background properties into one declaration.
  • Order guide: background: [color] [image] [position] / [size] [repeat] [origin] [clip] [attachment];
  • You don’t need to include all parts only what you use.

Code Block Loading...

Fallback color when image fails

  • Approach: Place a color after the image to ensure legibility if the image can’t load.

Code Block Loading...

Example