CSS Backgrounds

Background Color

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

div {
  background-color: lightgray;
}

Background Image

The background-image property adds an image behind an element.

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

Background Repeat

The background-repeat property controls if and how the background image repeats within an element.

  • repeatDefault. Tiles the background image both horizontally and vertically to fill the element.
  • no-repeat – Displays the background image only once without repeating.
  • repeat-x – Repeats the background image horizontally (left to right) but not vertically.
  • repeat-y – Repeats the background image vertically (top to bottom) but not horizontally.
div {
  background-repeat: no-repeat;
}

In the example above, the background image will be shown only once and will not tile across the element.

Background Position

Position the background image using keywords or coordinates:

div {
  background-position: center center;
}

Background Size

Control how the image fits:

  • cover – fill entire area
  • contain – fit inside without cropping
  • Custom values: px, %, etc.
div {
  background-size: cover;
}

Shorthand Property

Combine all background properties into one line:

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

Transparent and Opaque Backgrounds

You can control the transparency of a background using RGBA color values or the opacity property.

Using RGBA:

div {
background-color: rgba(0, 0, 255, 0.3); /* blue with 30% opacity */
}

Using Opacity:

div {
background-color: blue;
opacity: 0.5; /* affects entire element */
}

Practice Prompt

Create a <div> with:

  • A light blue background color
  • A centered background image
  • No repeat
  • The image should cover the full element
<div style={{
  background: "url('your-image.jpg') no-repeat center/cover lightblue",
  height: "300px",
  width: "100%",
  border: "1px solid #ccc"
}}>
  Styled Background
</div>

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic