Niveau 9 — Backgrounds

Les Backgrounds

Maîtrisez les arrière-plans : couleurs, images, gradients, motifs, textures et bien plus encore pour donner vie à vos interfaces.

1. Comprendre les Backgrounds

En une phrase : Les propriétés background contrôlent l'apparence de l'arrière-plan d'un élément, de la couleur de fond aux images complexes, gradients et motifs.

Les backgrounds sont l'un des outils les plus puissants de CSS. Ils permettent de créer des effets visuels impressionnants sans aucune image externe — uniquement avec du CSS pur.

Les propriétés de background se déclarent sur n'importe quel élément et sont héritées par défaut. Elles se combinent en couches, comme des feuilles transparentes superposées.

Propriété Description Valeurs principales
background-color Couleur de fond unie named, hex, rgb, hsl
background-image Image ou gradient en arrière-plan url(), linear-gradient(), radial-gradient()
background-repeat Contrôle la répétition de l'image repeat, no-repeat, repeat-x, repeat-y
background-position Position de l'image dans la boîte center, top left, 50% 50%
background-size Taille de l'image de fond auto, cover, contain, lengths
background-origin Point de départ de l'image padding-box, border-box, content-box
background-clip Zone de rendu du background border-box, padding-box, content-box, text
background-attachment Comportement au scroll scroll, fixed, local
background Shorthand (toutes les propriétés) Combinaison de toutes les valeurs
L'ordre de superposition : Les backgrounds se empilent comme des calques dans Photoshop. Le premier déclaré est au dessus, le dernier est en dessous. La couleur de fond est toujours la couche la plus basse.

2. Syntaxe détaillée

2.1 background-color — La couleur de fond

Définition : Définit la couleur unie de l'arrière-plan d'un élément. C'est la base de tout background.
/* Couleurs nommées */
.boite {
  background-color: red;
  background-color: transparent;  /* Transparents — défaut */
}

/* Hexadécimal */
.boite {
  background-color: #ff0000;      /* Rouge */
  background-color: #f00;         /* Rouge raccourci */
  background-color: #ff6b6b;      /* Rouge plus doux */
}

/* RGB / RGBA */
.boite {
  background-color: rgb(255, 0, 0);
  background-color: rgb(255 0 0);         /* Syntaxe moderne */
  background-color: rgba(255, 0, 0, 0.5); /* Avec transparence */
}

/* HSL / HSLA */
.boite {
  background-color: hsl(0, 100%, 50%);
  background-color: hsl(0 100% 50%);         /* Syntaxe moderne */
  background-color: hsla(0, 100%, 50%, 0.5); /* Avec transparence */
}

/* currentColor — hérite la couleur du texte */
.boite {
  background-color: currentColor;
}

/* Dégradé léger avec hsl */
.boite-douce {
  background-color: hsl(210 100% 95%);
}

Démonstration : Formats de couleurs

#3b82f6
rgb(16 185 129)
hsl(270 80% 60%)
hsla(340 / 0.8)

2.2 background-image — Images et gradients

Définition : Définit une ou plusieurs images en arrière-plan. Accepte une URL vers une image ou une fonction de gradient CSS.
/* Image simple */
.boite {
  background-image: url('pattern.png');
}

/* Gradient linéaire */
.boite {
  background-image: linear-gradient(to right, #ff6b6b, #4ecdc4);
}

/* Gradient radial */
.boite {
  background-image: radial-gradient(circle, #ff6b6b, #4ecdc4);
}

/* Gradient conique */
.boite {
  background-image: conic-gradient(#ff6b6b, #4ecdc4, #45b7d1, #ff6b6b);
}

/* Multiples backgrounds (séparés par une virgule) */
.boite {
  background-image:
    url('overlay.png'),
    linear-gradient(to bottom, #fff, #000);
}

/* Avec fallback couleur */
.boite {
  background-color: #e2e8f0;  /* Avant le chargement de l'image */
  background-image: url('hero.jpg');
}

Les Gradients en détail

Gradient linéaire : Crée un dégradé progressif le long d'une ligne droite.
/* Direction */
linear-gradient(to right, red, blue)       /* Gauche → droite */
linear-gradient(to bottom right, red, blue) /* Coin supérieur gauche → coin inférieur droit */
linear-gradient(45deg, red, blue)           /* Angle de 45 degrés */

/* Couleurs avec stops */
linear-gradient(to right, red 0%, blue 50%, green 100%)
linear-gradient(135deg, #667eea 0%, #764ba2 100%)

/* Bandes dures (pas de transition) */
linear-gradient(to right, red 33%, blue 33%, blue 66%, green 66%)
Gradient radial : Crée un dégradé circulaire ou elliptique depuis un point central.
/* Cercle depuis le centre */
radial-gradient(circle, red, blue)

/* Ellipse (défaut) */
radial-gradient(ellipse, red, blue)

/* Position et taille */
radial-gradient(circle at top left, red, blue)
radial-gradient(circle at 30% 70%, red 0%, blue 100%)

/* Taille au plus proche/loin du coin */
radial-gradient(closest-side circle, red, blue)
radial-gradient(farthest-corner circle, red, blue)
Gradient conique : Crée un dégradé circulaire autour d'un point central, comme une roue.
/* Roue de couleurs */
conic-gradient(red, orange, yellow, green, blue, indigo, violet, red)

/* Position */
conic-gradient(from 0deg at 50% 50%, red, blue, red)

/* Bandes dures — diagramme secteur */
conic-gradient(red 0deg 120deg, blue 120deg 240deg, green 240deg 360deg)

/* Utilisé pour un sélecteur circulaire */
.conic-progress {
  background: conic-gradient(#3b82f6 0% 75%, #e5e7eb 75% 100%);
  border-radius: 50%;
}

Démonstration : Les trois types de gradients

linear-gradient
radial-gradient
conic-gradient

2.3 background-repeat — Répétition

Définition : Contrôle comment une image de fond se répète quand elle ne couvre pas toute la surface.
/* Valeurs principales */
.boite { background-repeat: repeat; }    /* Répète sur les deux axes (défaut) */
.boite { background-repeat: repeat-x; }  /* Répète horizontalement */
.boite { background-repeat: repeat-y; }  /* Répète verticalement */
.boite { background-repeat: no-repeat; } /* Pas de répétition */
.boite { background-repeat: round; }     /* Répète ET ajuste pour remplir sans coupure */
.boite { background-repeat: space; }     /* Répète avec espacement uniforme */
repeat (défaut) :         repeat-x :            no-repeat :
┌───┬───┬───┬───┐       ┌───┬───┬───┬───┐     ┌───┬───┬───┬───┐
│ ◆ │ ◆ │ ◆ │ ◆ │       │ ◆ │ ◆ │ ◆ │ ◆ │     │ ◆ │   │   │   │
├───┼───┼───┼───┤       └───┴───┴───┴───┘     │   │   │   │   │
│ ◆ │ ◆ │ ◆ │ ◆ │       (une seule rangée)    │   │   │   │   │
├───┼───┼───┼───┤                               │   │   │   │   │
│ ◆ │ ◆ │ ◆ │ ◆ │                             └───┴───┴───┴───┘
└───┴───┴───┴───┘                             (une seule copie)

round :                   space :
┌───┬───┬───┬───┐       ┌───┬───┬───┬───┐
│ ◆ │ ◆ │ ◆ │ ◆ │       │ ◆ │ ◆ │ ◆ │ ◆ │
├───┼───┼───┼───┤       │   │   │   │   │
│ ◆ │ ◆ │ ◆ │ ◆ │       │ ◆ │ ◆ │ ◆ │ ◆ │
└───┴───┴───┴───┘       └───┴───┴───┴───┘
(ajuste la taille)      (ajuste l'espacement)

Comparaison des modes de répétition

Démonstration : Modes de répétition

repeat (défaut)
repeat-x
repeat-y
no-repeat

2.4 background-position — Position

Définition : Définit la position initiale de l'image de fond par rapport à la boîte de positionnement.
/* Mots-clés */
.boite { background-position: center; }
.boite { background-position: top left; }
.boite { background-position: bottom right; }
.boite { background-position: top center; }
.boite { background-position: left center; }

/* Pourcentages — 0% 0% = haut gauche, 100% 100% = bas droite */
.boite { background-position: 50% 50%; }   /* = center */
.boite { background-position: 25% 75%; }   /* Haut-gauche en X, bas-gauche en Y */

/* Longueurs — offset depuis le coin supérieur gauche */
.boite { background-position: 20px 40px; }
.boite { background-position: 1rem 2rem; }

/* Combinaison keyword + longueur */
.boite { background-position: center 20px; }  /* Centré horizontalement, 20px du haut */
.boite { background-position: right 10px bottom 20px; }

/* 4 valeurs — position précise de chaque coin */
.boite { background-position: top 10px left 20px; }

Démonstration : Positions de background

center center
top left
bottom right
25% 75%

2.5 background-size — Taille

Définition : Contrôle la taille de l'image de fond. Par défaut, l'image garde sa taille originale (auto).
/* Valeurs principales */
.boite { background-size: auto; }           /* Taille originale (défaut) */
.boite { background-size: cover; }          /* Couvre toute la zone, découpe si besoin */
.boite { background-size: contain; }        /* Contient toute l'image, espaces si besoin */

/* Longueurs */
.boite { background-size: 200px 100px; }    /* Largeur × Hauteur */
.boite { background-size: 50% 50%; }        /* Pourcentages */

/* Un seul pourcentage = largeur, hauteur proportionnelle */
.boite { background-size: 50%; }
cover :                      contain :
┌──────────────────┐         ┌──────────────────┐
│┌────────────────┐│         │  ┌────────────┐  │
││                ││         │  │            │  │
││   IMAGE        ││         │  │   IMAGE    │  │
││   (remplit,    ││         │  │  (contient, │  │
││    coupée)     ││         │  │   espaces) │  │
││                ││         │  │            │  │
│└────────────────┘│         │  └────────────┘  │
└──────────────────┘         └──────────────────┘
Aucun espace vide             Peut avoir des espaces
Peut découper l'image        L'image est toujours entière

Différence entre cover et contain

Démonstration : background-size

auto (défaut)
cover
contain
cover vs contain :
  • cover — idéal pour les hero sections et images plein écran. L'image remplit tout mais peut être rognée.
  • contain — idéal pour les logos et icônes. L'image est toujours entière mais peut laisser des espaces.

2.6 background-origin — Point de départ

Définition : Définit depuis quel bord de la boîte l'image de fond commence à se dessiner.
/* padding-box (défaut) — l'image commence au bord intérieur du padding */
.boite { background-origin: padding-box; }

/* border-box — l'image commence au bord extérieur de la border */
.boite { background-origin: border-box; }

/* content-box — l'image commence au bord du contenu */
.boite { background-origin: content-box; }
border-box :    ┌─── BORDER ───┐
                │ ┌── PADDING ─┐│
                │ │ ┌─ CONTENT ┐││
                │ │ │          │││
                ◄ │ │  ◄ IMG ► │││
                │ │ │          │││
                │ │ └──────────┘││
                │ └─────────────┘│
                └────────────────┘

padding-box :   ┌─── BORDER ───┐
                │ ┌── PADDING ─┐│
                │ │ ◄─ IMG ──► ││
                │ │ ┌─ CONTENT ┐││
                │ │ │          │││
                │ │ └──────────┘││
                │ └─────────────┘│
                └────────────────┘

content-box :   ┌─── BORDER ───┐
                │ ┌── PADDING ─┐│
                │ │ ┌─ CONTENT ┐││
                │ │ │ ◄─ IMG ─►│││
                │ │ └──────────┘││
                │ └─────────────┘│
                └────────────────┘

Les trois modes de background-origin

2.7 background-clip — Zone de rendu

Définition : Définit jusqu'où le background s'étend. Contrairement à background-origin, il peut cacher le rendu du background.
/* border-box (défaut) — le background se rend sous la border */
.boite { background-clip: border-box; }

/* padding-box — le background s'arrête au bord intérieur de la border */
.boite { background-clip: padding-box; }

/* content-box — le background s'arrête au bord du contenu */
.boite { background-clip: content-box; }

/* text — le background ne se rend QUE sur le texte (magique !) */
.boite { background-clip: text; }
.boite {
  background-clip: text;
  -webkit-background-clip: text;  /* Préfixe WebKit nécessaire */
  color: transparent;
}

Démonstration : background-clip: text

Texte avec gradient

Le gradient ne se rend que sur les lettres !

2.8 background-attachment — Comportement au scroll

Définition : Contrôle si le background défile avec le contenu ou reste fixe par rapport à la fenêtre.
/* scroll (défaut) — le background défile avec l'élément */
.boite { background-attachment: scroll; }

/* fixed — le background reste fixe par rapport à la viewport */
.boite { background-attachment: fixed; }

/* local — le background défile avec le contenu interne de l'élément */
.boite { background-attachment: local; }
scroll (défaut) :       fixed :                local :
┌─────────────┐        ┌─────────────┐        ┌─────────────┐
│  📋 scroll  │        │  📋 scroll  │        │  📋 scroll  │
│  ↕ avec     │        │  ↕ avec     │        │  ↕ avec     │
│  le contenu │        │  le contenu │        │  le contenu │
├─────────────┤        ├─────────────┤        ├─────────────┤
│  BG scroll  │        │  BG fixe    │        │  BG scroll  │
│  ↕ avec     │        │  ✗ ne bouge │        │  ↕ avec le  │
│  l'élément  │        │   pas       │        │  CONTENU    │
└─────────────┘        └─────────────┘        └─────────────┘

Les trois modes de background-attachment

2.9 background — Shorthand

Définition : Raccourci qui permet de définir toutes les propriétés de background en une seule déclaration.
/* Ordre recommandé :
   background: color image repeat position / size origin clip attachment */

/* Exemple simple */
.boite {
  background: #3b82f6 url('pattern.png') no-repeat center / cover;
}

/* Gradient avec position et taille */
.boite {
  background:
    linear-gradient(135deg, #667eea 0%, #764ba2 100%)
    center / cover no-repeat;
}

/* Remettre tout au défaut */
.boite {
  background: transparent none no-repeat 0% 0% / auto scroll padding-box border-box;
}

/* Réinitialiser complètement */
.boite {
  background: initial;
}
Piège du shorthand : Quand on utilise background, toutes les propriétés non spécifiées sont réinitialisées à leurs valeurs initiales. Si vous définissez background après background-size, la taille sera écrasée.
/* ATTENTION — l'ordre compte */
.boite {
  background-size: cover;       /* Défini */
  background: url('img.jpg');   /* background-size repasse à auto ! */
}

/* CORRECT — tout dans le shorthand */
.boite {
  background: url('img.jpg') center / cover no-repeat;
}

3. Visualisation

3.1 Couche de background — Modèle complet

┌─ border-box ─────────────────────────────────────┐
│  border                                          │
│  ┌─ padding-box ───────────────────────────────┐  │
│  │  padding                                    │  │
│  │  ┌─ content-box ─────────────────────────┐  │  │
│  │  │                                        │  │  │
│  │  │  Couche 1 : background-color           │  │  │
│  │  │  Couche 2 : background-image #1        │  │  │
│  │  │  Couche 3 : background-image #2        │  │  │
│  │  │  ...                                   │  │  │
│  │  │                                        │  │  │
│  │  └────────────────────────────────────────┘  │  │
│  │                                              │  │
│  └──────────────────────────────────────────────┘  │
└────────────────────────────────────────────────────┘

Propriétés associées :
  background-origin  → par rapport à quelle zone l'image se positionne
  background-clip    → jusqu'où le rendu s'étend
  background-size    → taille de chaque couche
  background-position → position de chaque couche

Modèle de couche de background

3.2 cover vs contain vs auto

Image originale (400×300) dans un conteneur (300×200) :

auto (défaut) :            cover :               contain :
┌────────────────┐        ┌────────────────┐    ┌────────────────┐
│ ┌──────────┐   │        │ ┌──────────────┐│    │                │
│ │          │   │        │ │              ││    │  ┌──────────┐  │
│ │  IMAGE   │   │        │ │   IMAGE      ││    │  │          │  │
│ │  400×300 │   │        │ │  (remplie,   ││    │  │  IMAGE   │  │
│ └──────────┘   │        │ │   rognée)    ││    │  │  (entière│  │
│                │        │ └──────────────┘│    │  │   mais   │  │
└────────────────┘        └────────────────┘    │  │  petite) │  │
Déborde !                 Pas d'espace          │  └──────────┘  │
                                                └────────────────┘
                                                Espaces vides

Comparaison des trois modes de taille

3.3 Multiples backgrounds

Déclaration :
background-image:
  url('overlay.png'),          ← Couche 1 (devant)
  linear-gradient(...),        ← Couche 2
  url('texture.jpg');          ← Couche 3 (derrière)

Rendu (coupe transversale) :
┌──────────────────────────────┐
│  overlay.png                 │ ← Couche 1 (devant)
│  ┌────────────────────────┐  │
│  │  gradient              │  │ ← Couche 2
│  │  ┌──────────────────┐  │  │
│  │  │  texture.jpg     │  │  │ ← Couche 3 (derrière)
│  │  └──────────────────┘  │  │
│  └────────────────────────┘  │
└──────────────────────────────┘

Chaque couche peut avoir :
  position  / size  — séparés par un /
  repeat            — pour la répétition

Superposition de multiples backgrounds

4. Exemples progressifs

4.1 Hero section avec gradient

Section héroïque moderne

.hero {
  min-height: 80vh;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  color: white;

  /* Gradient diagonal moderne */
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);

  /* Texte superposé avec effet de voile */
  position: relative;
}

.hero::before {
  content: '';
  position: absolute;
  inset: 0;
  background: url('hero-image.jpg') center / cover no-repeat;
  opacity: 0.3;
  z-index: 0;
}

.hero > * {
  position: relative;
  z-index: 1;
}

Titre Héroïque

Un superbe gradient en arrière-plan

4.2 Motifs de fond en CSS pur

Atelier de création de motifs

/* Rayures horizontales */
.stripes {
  background: repeating-linear-gradient(
    0deg,
    #3b82f6,
    #3b82f6 10px,
    #60a5fa 10px,
    #60a5fa 20px
  );
}

/* Pointillés */
.dots {
  background-image: radial-gradient(#3b82f6 2px, transparent 2px);
  background-size: 20px 20px;
}

/* Damier */
.checkerboard {
  background-color: #fff;
  background-image:
    linear-gradient(45deg, #e5e7eb 25%, transparent 25%, transparent 75%, #e5e7eb 75%),
    linear-gradient(45deg, #e5e7eb 25%, transparent 25%, transparent 75%, #e5e7eb 75%);
  background-size: 40px 40px;
  background-position: 0 0, 20px 20px;
}

/* Zigzag */
.zigzag {
  background:
    linear-gradient(135deg, #3b82f6 25%, transparent 25%) -50px 0,
    linear-gradient(225deg, #3b82f6 25%, transparent 25%) -50px 0,
    linear-gradient(315deg, #3b82f6 25%, transparent 25%),
    linear-gradient(45deg, #3b82f6 25%, transparent 25%);
  background-size: 100px 100px;
  background-color: #93c5fd;
}
Rayures
Pointillés
Damier
Zigzag

4.3 Effets de texture

Textures avec gradients et mix-blend-mode

/* Bruit grainé */
.grain {
  background-color: #f8fafc;
  background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noise'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noise)' opacity='0.05'/%3E%3C/svg%3E");
}

/* Texture papier */
.paper {
  background-color: #fffef5;
  background-image:
    radial-gradient(ellipse at 50% 50%, rgba(0,0,0,0.03) 1px, transparent 1px);
  background-size: 4px 4px;
}

/* Ombre interne (texture de profondeur) */
.depth {
  background: linear-gradient(
    to bottom,
    rgba(0,0,0,0.1) 0%,
    transparent 30%,
    transparent 70%,
    rgba(0,0,0,0.05) 100%
  ),
  #f8fafc;
}

4.4 Background blend modes

Combiner des backgrounds avec mix-blend-mode

/* Superposition avec blend mode */
.blend-overlay {
  background:
    linear-gradient(135deg, #667eea, #764ba2),
    url('photo.jpg') center / cover;
  background-blend-mode: overlay;
}

/* Exemples de blend modes */
.blend-multiply { background-blend-mode: multiply; }
.blend-screen   { background-blend-mode: screen; }
.blend-overlay  { background-blend-mode: overlay; }
.blend-darken   { background-blend-mode: darken; }
.blend-lighten  { background-blend-mode: lighten; }

/* Effet de vignette */
.vignette::after {
  content: '';
  position: absolute;
  inset: 0;
  background: radial-gradient(
    ellipse at center,
    transparent 50%,
    rgba(0,0,0,0.5) 100%
  );
}
multiply
screen
overlay
darken

4.5 Multi-backgrounds créatifs

Combiner plusieurs couches de background

/* Carte avec texture + gradient + motif */
.carte-texturee {
  background:
    /* Couche 1 : motif de points */
    radial-gradient(circle, #e5e7eb 1px, transparent 1px),
    /* Couche 2 : gradient diagonal */
    linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%),
    /* Couche 3 : couleur de base */
    #ffffff;
  background-size:
    20px 20px,    /* Taille du motif */
    100% 100%,    /* Gradient plein écran */
    100% 100%;    /* Couleur de base */
}

/* Bandeau décoratif */
.bandeau {
  background:
    linear-gradient(135deg, transparent 40%, rgba(255,255,255,0.1) 40%),
    linear-gradient(225deg, transparent 40%, rgba(255,255,255,0.1) 40%),
    linear-gradient(135deg, #3b82f6, #8b5cf6);
  background-size: 60px 60px;
}
Carte texturée

Carte texturée

Plusieurs couches de background combinées

Bandeau décoratif

Bandeau décoratif

Gradient + motif de chevrons

4.6 Background parallaxe avec fixed

Effet parallaxe simple

/* Section avec background fixe (effet parallaxe) */
.section-parallax {
  min-height: 50vh;
  background:
    linear-gradient(rgba(0,0,0,0.4), rgba(0,0,0,0.4)),
    url('paysage.jpg') center / cover no-repeat fixed;
  display: grid;
  place-items: center;
  color: white;
  text-align: center;
}

/* Alternance de sections */
.contenu {
  padding: 4rem 2rem;
  max-width: 800px;
  margin: 0 auto;
}

5. Erreurs fréquentes

Erreur 1 : Oublier le fallback couleur
/* FAUX — écran blanc pendant le chargement de l'image */
.boite {
  background: url('hero.jpg') center / cover no-repeat;
}

/* CORRECT — couleur de fond comme fallback */
.boite {
  background-color: #1e293b;  /* S'affiche immédiatement */
  background: url('hero.jpg') center / cover no-repeat;
}
Erreur 2 : Confondre background-clip et background-origin
/* background-origin = OÙ l'image commence (position de départ) */
.boite { background-origin: content-box; }

/* background-clip = JUSQUE OÙ le rendu s'étend (zone de rendu) */
.boite { background-clip: padding-box; }

/* Les deux peuvent être différents ! */
.boite {
  background-origin: border-box;    /* Image part du bord de la border */
  background-clip: content-box;     /* Mais le rendu s'arrête au contenu */
}
Erreur 3 : Utiliser background-size sans background-image
/* FAUX — background-size n'a aucun effet sans image */
.boite {
  background-color: #3b82f6;
  background-size: cover;  /* Ignoré ! */
}

/* CORRECT — background-size ne s'applique qu'aux images/gradients */
.boite {
  background: linear-gradient(#3b82f6, #8b5cf6);
  background-size: 100% 200%;  /* Fonctionne car c'est un gradient */
}
Erreur 4 : Ordre incorrect dans le shorthand
/* FAUX — la taille doit être après la position avec un / */
.boite {
  background: url('img.jpg') cover center;  /* Erreur de syntaxe */
}

/* CORRECT — position / taille */
.boite {
  background: url('img.jpg') center / cover no-repeat;
}
Erreur 5 : background-clip: text sans color: transparent
/* FAUX — le texte est opaque, on ne voit pas le gradient */
.boite {
  background: linear-gradient(to right, red, blue);
  background-clip: text;
}

/* CORRECT — transparence du texte pour révéler le gradient */
.boite {
  background: linear-gradient(to right, red, blue);
  background-clip: text;
  -webkit-background-clip: text;  /* Préfixe nécessaire */
  color: transparent;
}
Erreur 6 : Shorthand qui écrase les propriétés précédentes
/* FAUX — le shorthand réinitialise tout */
.boite {
  background-size: cover;     /* Défini */
  background-color: #fff;     /* OK */
  background: url('img.jpg'); /* Réinitialise background-size à auto ! */
}

/* CORRECT — utiliser le shorthand complet */
.boite {
  background: #fff url('img.jpg') center / cover no-repeat;
}
Erreur 7 : Ne pas tenir compte de la performance
/* FAUX — trop de gradients et de couches */
.boite {
  background:
    linear-gradient(...),
    radial-gradient(...),
    url('texture1.png'),
    url('texture2.png'),
    url('texture3.png'),
    url('texture4.png');  /* Beaucoup trop de couches ! */
}

/* CORRECT — garder un nombre raisonnable de couches */
.boite {
  background:
    url('texture.png'),
    linear-gradient(135deg, #667eea, #764ba2);
  /* 2-3 couches maximum pour la performance */
}

6. Bonnes pratiques

Les règles d'or des backgrounds :
  • Toujours un fallback couleur — définir background-color avant background-image.
  • Préférer les gradients CSS aux images pour les motifs simples — plus performants, scalables.
  • Utiliser background-size: cover pour les hero sections, contain pour les logos.
  • Limiter le nombre de couches — 2-3 maximum pour les performances.
  • Préfixe -webkit-background-clip: text — nécessaire pour le clipping sur le texte.
  • Optimiser les images de fond — formats WebP/AVIF, dimensions adaptées.
  • Préférer background-blend-mode aux images superposées avec opacity.
  • Utiliser background-attachment: fixed avec parcimonie — peut causer des problèmes de performance mobile.
Situation Propriété recommandée
Hero section plein écran background-size: cover; background-position: center
Logo centré background-size: contain; background-repeat: no-repeat
Motif répétable background-repeat: repeat; background-size: [taille motif]
Effet parallaxe background-attachment: fixed
Texte avec gradient background-clip: text; color: transparent
Texture sous le contenu background-origin: content-box; background-clip: content-box
Couche de couleur sur image background-blend-mode: multiply/screen
Vignette sur image Gradient radial avec ::after

7. Mini-défi

Exercice 1 : Gradient moderne

Crée un fond dégradé qui va du violet au bleu, en diagonal (135 degrés) :

Solution :

.gradient-diagonal {
  background: linear-gradient(135deg, #8b5cf6, #3b82f6);
}

Exercice 2 : Motif de points

Crée un fond avec des points réguliers espacés de 30px, bleus de 2px de diamètre :

Solution :

.motif-points {
  background-image: radial-gradient(#3b82f6 2px, transparent 2px);
  background-size: 30px 30px;
}

Exercice 3 : Cover parfait

Crée une section de 400px de haut avec une image de fond qui couvre toute la zone, sans répétition, centrée :

Solution :

.section-cover {
  height: 400px;
  background-color: #1e293b;
  background-image: url('paysage.jpg');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  /* OU en shorthand : */
  background: #1e293b url('paysage.jpg') center / cover no-repeat;
}

Exercice 4 : Texte gradient

Crée un titre dont le texte est rempli par un dégradé arc-en-ciel :

Solution :

.titre-arcenciel {
  background: linear-gradient(90deg, red, orange, yellow, green, blue, indigo, violet);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  font-size: 3rem;
  font-weight: 900;
}

Exercice 5 : Damier

Crée un damier de 50×50px avec les couleurs blanche et grise :

Solution :

.damier {
  background-color: #ffffff;
  background-image:
    linear-gradient(45deg, #e5e7eb 25%, transparent 25%, transparent 75%, #e5e7eb 75%),
    linear-gradient(45deg, #e5e7eb 25%, transparent 25%, transparent 75%, #e5e7eb 75%);
  background-size: 50px 50px;
  background-position: 0 0, 25px 25px;
}

Exercice 6 : Double background

Combina un gradient vertical (bleu vers blanc) avec un motif de rayures horizontales semi-transparentes :

Solution :

.double-bg {
  background:
    repeating-linear-gradient(
      0deg,
      rgba(255,255,255,0.1) 0px,
      rgba(255,255,255,0.1) 2px,
      transparent 2px,
      transparent 10px
    ),
    linear-gradient(to bottom, #3b82f6, #ffffff);
  background-size: 100% 100%;
}

8. Projet d'application

Projet : Page avec backgrounds créatifs

Crée un fichier index.html et backgrounds.css qui implémentent une page avec 3 sections distinctes utilisant les propriétés de background :

HTML requis :

  • Un <header class="hero"> — section héroïque avec gradient et overlay
  • Un <main> contenant :
  • Un <section class="features"> — avec motif de fond en points
  • Un <section class="testimonials"> — avec texture papier
  • Un <section class="cta"> — avec multi-backgrounds
  • Un <footer> — avec gradient sombre

CSS requis :

  • .hero : gradient 135deg, min-height 80vh, centered text, ::before avec overlay
  • .features : radial-gradient pour motif de points, padding généreux
  • .testimonials : texture papier avec micro-dots, background-color crème
  • .cta : multi-backgrounds (gradient + motif), background-blend-mode
  • footer : gradient vertical sombre, text white
  • Utiliser background-size, background-position, background-repeat sur chaque section

Objectif : Démontrer la maîtrise des propriétés de background dans un cas réel avec plusieurs sections visuellement distinctes.

9. Révision

Quiz rapide

  1. Quelle est la différence entre background-origin et background-clip ?
  2. Quelle valeur de background-size remplit toute la zone sans laisser d'espace vide ?
  3. Quelle valeur de background-size contient toute l'image sans la rogners ?
  4. Comment créer un dégradé diagonal de gauche à droite ?
  5. Quelle propriété permet de faire défiler le background indépendamment du contenu ?
  6. Comment rendre le texte transparent pour laisser apparaître le gradient en arrière-plan ?
  7. Comment créer un motif de points réguliers avec CSS ?
  8. Quel est l'ordre correct dans le shorthand background pour la taille ?
  9. Quelle propriété CSS permet de combiner visuellement plusieurs couches de background ?
  10. Pourquoi faut-il toujours définir background-color avant background-image ?
Réponses :
  1. background-origin définit depuis quel bord l'image se positionne. background-clip définit jusqu'où le rendu du background s'étend.
  2. cover
  3. contain
  4. linear-gradient(to right, couleur1, couleur2) ou linear-gradient(90deg, couleur1, couleur2)
  5. background-attachment: fixed
  6. color: transparent avec background-clip: text
  7. radial-gradient(couleur 2px, transparent 2px) avec background-size: 20px 20px
  8. position / taille (séparés par un slash) — ex: center / cover
  9. background-blend-mode
  10. Parce que le shorthand background réinitialise toutes les propriétés. Le fallback couleur doit être défini séparément ou en premier dans le shorthand.