Retour au cours

Lesson 20: Controlling Background Size and Attachment

**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.)*

20. Controlling Background Size and Attachment

When using large background images, you need granular control over how they scale and behave when the user scrolls.

Background Size (background-size)

This property defines how the background image is scaled relative to the container.

ValueDescription
auto (default)Displays the image in its original size.
coverScales the image to be as large as possible so that the background area is completely covered by the background image. The image aspect ratio is maintained. (Most common for full-screen headers)
containScales the image to be as large as possible without cropping or stretching. The image aspect ratio is maintained, but it may leave empty space if the aspect ratios don't match.
Dimensionsbackground-size: 200px 100px; (Width Height)

css .full-screen-bg { background-image: url('image.jpg'); background-size: cover; /* Ensures the element is always filled */ background-position: center; }

Background Attachment (background-attachment)

This property determines whether the background image scrolls with the content or stays fixed in place.

ValueDescription
scroll (default)The background image moves when the page scrolls.
fixedThe background image stays fixed relative to the viewport. This creates a powerful 'parallax' like effect.
localThe background image scrolls with the element's content (useful if the element itself has internal scrolling).

css body { background-image: url('stars.jpg'); background-attachment: fixed; /* Creates a fixed, non-moving background */ background-size: cover; }