CSS Backgrounds


🔹 What are CSS Backgrounds?

CSS Background properties allow you to control the background appearance of elements — including colors, images, positioning, repeating, attachment, and more.


🔸 Common CSS Background Properties

Property Description
background-color Sets background color
background-image Sets a background image
background-repeat Repeats the background image
background-position Sets the position of the background image
background-size Specifies size of background image
background-attachment Fixes background while scrolling
background (shorthand) Combines all background properties

🔸 1. background-color

Sets the background color of an element.

div {
  background-color: lightblue;
}

🔸 2. background-image

Adds an image as the background.

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

🔸 3. background-repeat

Defines how the image repeats:

background-repeat: repeat;       /* default */
background-repeat: no-repeat;    /* no repeating */
background-repeat: repeat-x;     /* horizontal */
background-repeat: repeat-y;     /* vertical */

🔸 4. background-position

Sets the starting position of the image:

background-position: top right;

You can use values like left, right, center, bottom, or in px/%.


🔸 5. background-size

Specifies the size of the background image:

background-size: cover;      /* Fill entire element */
background-size: contain;    /* Fit within element */
background-size: 100px 200px; /* Custom size */

🔸 6. background-attachment

Controls scroll behavior:

background-attachment: scroll;   /* default */
background-attachment: fixed;    /* image stays in place */
background-attachment: local;

🔸 7. background (Shorthand)

div {
  background: url('img.jpg') no-repeat center center / cover;
}

🟢 Combines all background properties in one line.


Practice Questions

Q1. Set a yellow background color for a div.

Q2. Add a background image named bg.jpg.

Q3. Prevent the image from repeating.

Q4. Center the image horizontally and vertically.

Q5. Resize the background image to fully cover the div.

Q6. Fix the image in the background while scrolling.

Q7. Use a different background color for a header section.

Q8. Create a gradient overlay on a background image.

Q9. Use background-size: contain for a logo section.

Q10. Write shorthand to apply image + color + position.


Go Back Top