CSS for Web Development

0% completed

Previous
Next
Background Shorthand

Background shorthand lets you combine multiple background properties into one line. Instead of writing each property separately, you can set the background color, image, repeat, attachment, and position all at once. This makes your CSS cleaner and easier to manage.

Syntax

Follow the code block below to use the background shorthand in CSS:

background: background-color background-image background-repeat background-attachment background-position;

Explanation:

  • background-color: Sets the solid color behind an element.
  • background-image: Adds an image as the background.
  • background-repeat: Controls if the background image repeats (options like repeat, no-repeat, etc.).
  • background-attachment: Specifies whether the background image scrolls with the page or is fixed (e.g., scroll, fixed).
  • background-position: Sets the starting position of the background image.

Example 1: Basic Background Shorthand

In this example, we set a background color, add a background image, and control the image repeat and position using the shorthand property.

HTML

. . . .

Explanation:

  • Background Color:
    • #f0f8ff: Sets a light blue background color.
  • Background Image:
  • Background Repeat:
    • no-repeat: The image does not repeat.
  • Background Position:
    • center: The image is centered in the element.
  • Outcome: The shorthand rule applies all the background styles together, making the CSS simpler.

Example 2: Detailed Background Shorthand

In this example, we use the background shorthand to also include the attachment property. This example shows how to set the background so that the image is fixed while you scroll.

HTML

. . . .

Explanation:

  • Background Color:
    • #ffe4e1: Sets a light pink background color.
  • Background Image:
  • Background Repeat:
    • no-repeat: Prevents the image from repeating.
  • Background Attachment:
    • fixed: Fixes the image so that it does not scroll with the rest of the page.
  • Background Position:
    • right: Positions the image at the right of the element.
  • Outcome: The element shows a fixed background image, combined using one shorthand property, creating a streamlined and manageable style.

This lesson demonstrates how to use the background shorthand to combine several properties into one concise rule. This approach simplifies your CSS and makes it easier to maintain.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next