Retour au cours

Lesson 21: The Background Shorthand Property

**La Maîtrise de CSS : De zéro à expert en 100 leçons** *(Alternative, slightly punchier version using a common French idiomatic structure for full coverage: CSS : Maîtrisez l'essentiel en 100 leçons, but the first option is closer to the original progression.)*

21. The Background Shorthand Property

CSS provides a powerful background shorthand property that allows you to define almost all background-related properties in a single line. This is the preferred method for clean, concise code.

The Shorthand Order (Generally)

While the order isn't strictly mandated, a conventional order is:

background: color image repeat attachment position / size;

Note: The size property (cover or dimensions) must be separated from position by a forward slash (/).

Shorthand Examples

Example 1: Simple Color and Image

css /* Longhand */ .long { background-color: black; background-image: url('logo.png'); background-repeat: no-repeat; }

/* Shorthand Equivalent */ .short { background: black url('logo.png') no-repeat; }

Example 2: Fixed, Centered, and Sized Background

css .hero-bg { /* Order: Color Image Repeat Attachment Position / Size */ background: #000 url('../img/bg.jpg') no-repeat fixed center center / cover; }

Tip: If you omit a property in the shorthand (like repeat or attachment), it will reset to its default value. If you only specify a color, everything else defaults to none or auto.

css .only-color { background: lightyellow; /* Resets image, repeat, etc., but sets color */ }