2R - CSS Background Properties

MDN background-position

Sets the initial position for each background image.

background-position: x-coordinate y-coordinate;

The x-coordinate is the image's distance away from the container's left edge, and the y-coordinate is its distance away from the top edge.

Possible Values

  • Edges

    • top
    • bottom
    • left
    • right
    • center
  • Percentages

    • background-position: x-coordinate % y-coordinate %;
  • Units

    • px
    • rem
    • em
    • vw
    • vh
    • etc
  • Multiple images

    • background-position: image 1, image 2, etc;

MDN background-attachment

Determines whether a background image is fixed within the viewport, or scrolls within its containing block.

Possible Values

  • fixed

    • Background is fixed relative to the viewport.
  • scroll

    • Background is fixed relative to the element itself, and does not scroll with its contents.
  • local

    • Background is fixed relative to the element's contents, which does scroll with its contents.

MDN background-size

Sets the size of the element's background image. Normally the image is either sized to fit within the available space or left to its default size.

Possible Values

  • cover

    • Completely fills its container while preserving its aspect ratio. Any parts of the image that extend beyond the container are cropped off.
  • contain

    • Fits the image within its container without stretching or cropping the image. Contain will not fill its container if the image is smaller than the container.
  • auto

    • Scales the image to 100% of its container width, with no additional sizing or cropping. The image will maintain its original dimensions.

MDN Edge Offset

The distance away from an edge when using the background-position property.

background-position: left/right <offset> top/bottom <offset>;

MDN Multiple Stack Order

The order in which images are specified within the CSS code is what determines the order that they are stacked on the web page.

Writing the code for the background images before the background color ensures that those images are stacked on top of that color.

CSS Background Summary

Background is a complex shorthand property that can use many of the other background properties at once. However learning how these properties work and using the shorthand creates the cleanest and more convenient CSS code to read.