Cours HTML et CSS · Module 9: CSS moderne

Cascade Layers - Contrôler l'ordre de la cascade CSS

21 min de lecture ·
Dans cette leçon4

Tu ajoutes une bibliothèque de composants à ton projet. Ses boutons ont un sélecteur du genre #app .btn.btn-primary, et ta simple classe .button perd face à lui en spécificité. Tu ajoutes !important, l'auteur de la bibliothèque fait de même, et commence alors une guerre où plus personne ne sait pourquoi le bouton a cette couleur. Les CSS Cascade Layers (@layer) sont une fonctionnalité CSS qui te permet de contrôler explicitement l'ordre de la cascade des styles. Elles permettent d'organiser le CSS en couches logiques avec une hiérarchie d'importance définie, ce qui simplifie considérablement la gestion de feuilles de style complexes.

Les bases des Cascade Layers

Que sont les Cascade Layers ?

Les Cascade Layers te permettent de définir des couches CSS nommées, où les styles des couches situées plus haut dans la hiérarchie prennent le dessus sur les styles des couches inférieures, indépendamment de la spécificité des sélecteurs. Voici quatre couches classiques :

/* Définition d'une couche et de ses styles */
@layer reset {
  * {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
  }
}

@layer base {
  body {
    font-family: 'Inter', sans-serif;
    line-height: 1.6;
    color: #333;
  }

  h1, h2, h3, h4, h5, h6 {
    margin-bottom: 0.5em;
    font-weight: 600;
  }
}

@layer components {
  .button {
    padding: 0.75rem 1.5rem;
    border: none;
    border-radius: 6px;
    background: #007bff;
    color: white;
    cursor: pointer;
  }
}

@layer utilities {
  .text-center { text-align: center; }
  .hidden { display: none; }
  .mt-4 { margin-top: 1rem; }
}

Sans déclaration séparée, c'est la première apparition d'un nom qui fixe l'ordre, donc reset se trouve tout en bas et utilities tout en haut. La classe .hidden de utilities l'emportera donc sur n'importe quelle règle de components, même plus spécifique. La spécificité ne compte qu'à l'intérieur d'une même couche. Retiens aussi que les styles ordinaires écrits en dehors des couches l'emportent sur toutes les couches.

Déclarer l'ordre des couches

Tu peux définir explicitement l'ordre des couches au début de la feuille de style, en une seule instruction courte terminée par un point-virgule :

/* Définition de l'ordre des couches - de la plus basse à la plus haute priorité */
@layer reset, base, layout, components, utilities;

/* Maintenant tu peux utiliser les couches dans n'importe quel ordre dans le code */

@layer utilities {
  .text-red { color: red; }
}

@layer reset {
  * { margin: 0; }
}

@layer components {
  .card {
    background: white;
    border: 1px solid #ddd;
    padding: 1rem;
  }
}

/* L'ordre des définitions dans le code n'a pas d'importance - seul l'ordre de la déclaration @layer compte */

L'ordre des blocs dans le code n'a pas d'importance, seul compte l'ordre de la déclaration @layer. Je te recommande de toujours commencer ta feuille de style par une telle ligne, car toute la hiérarchie est alors visible à un seul endroit, comme le plan des étages gravé à l'entrée d'une pyramide.

Techniques avancées des Cascade Layers

1. Couches imbriquées

Les couches peuvent contenir leurs propres couches. On enferme tout le framework dans une seule couche, et à l'intérieur, on organise son reset, sa base, sa mise en page et ses utilitaires :

@layer framework {
  /* Couches imbriquées dans la couche framework */
  @layer reset {
    *, *::before, *::after {
      box-sizing: border-box;
      margin: 0;
      padding: 0;
    }

    html {
      line-height: 1.15;
      -webkit-text-size-adjust: 100%;
    }
  }

  @layer base {
    body {
      font-family: system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
      font-size: 1rem;
      line-height: 1.6;
      color: #212529;
      background: #ffffff;
    }

    img, svg {
      display: block;
      max-width: 100%;
      height: auto;
    }

    button, input, select, textarea {
      font: inherit;
    }
  }

  @layer layout {
    .container {
      width: 100%;
      max-width: 1200px;
      margin: 0 auto;
      padding: 0 1rem;
    }

    .grid {
      display: grid;
      gap: 1rem;
    }

    .flex {
      display: flex;
      align-items: center;
      gap: 1rem;
    }

    @media (min-width: 768px) {
      .container {
        padding: 0 2rem;
      }

      .grid {
        grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
        gap: 2rem;
      }
    }
  }

  @layer components {
    /* Composants UI */
    .btn {
      --btn-padding: 0.75rem 1.5rem;
      --btn-border-radius: 6px;
      --btn-font-weight: 500;
      --btn-transition: all 0.2s ease;

      display: inline-flex;
      align-items: center;
      justify-content: center;
      padding: var(--btn-padding);
      border: 1px solid transparent;
      border-radius: var(--btn-border-radius);
      font-weight: var(--btn-font-weight);
      text-decoration: none;
      cursor: pointer;
      transition: var(--btn-transition);

      &:focus {
        outline: 2px solid transparent;
        box-shadow: 0 0 0 2px rgba(66, 153, 225, 0.5);
      }

      &:disabled {
        opacity: 0.6;
        cursor: not-allowed;
      }
    }

    .btn-primary {
      background: #007bff;
      color: white;
      border-color: #007bff;

      &:hover:not(:disabled) {
        background: #0056b3;
        border-color: #0056b3;
      }
    }

    .btn-secondary {
      background: #6c757d;
      color: white;
      border-color: #6c757d;

      &:hover:not(:disabled) {
        background: #545b62;
        border-color: #545b62;
      }
    }

    .btn-outline {
      background: transparent;
      color: #007bff;
      border-color: #007bff;

      &:hover:not(:disabled) {
        background: #007bff;
        color: white;
      }
    }

    /* Composant carte */
    .card {
      background: white;
      border: 1px solid #e9ecef;
      border-radius: 12px;
      overflow: hidden;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      transition: all 0.3s ease;

      &:hover {
        box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
        transform: translateY(-2px);
      }
    }

    .card-header {
      padding: 1.5rem;
      border-bottom: 1px solid #e9ecef;
      background: #f8f9fa;
    }

    .card-body {
      padding: 1.5rem;
    }

    .card-footer {
      padding: 1rem 1.5rem;
      border-top: 1px solid #e9ecef;
      background: #f8f9fa;
    }

    /* Composant alerte */
    .alert {
      --alert-padding: 1rem 1.5rem;
      --alert-border-radius: 8px;
      --alert-border-width: 1px;

      padding: var(--alert-padding);
      border: var(--alert-border-width) solid transparent;
      border-radius: var(--alert-border-radius);
      margin-bottom: 1rem;

      .alert-title {
        font-weight: 600;
        margin-bottom: 0.5rem;
      }

      &.alert-info {
        background: #e3f2fd;
        border-color: #2196f3;
        color: #0d47a1;
      }

      &.alert-success {
        background: #e8f5e8;
        border-color: #4caf50;
        color: #1b5e20;
      }

      &.alert-warning {
        background: #fff3e0;
        border-color: #ff9800;
        color: #e65100;
      }

      &.alert-error {
        background: #ffebee;
        border-color: #f44336;
        color: #b71c1c;
      }
    }
  }
}

/* Styles externes (priorité plus élevée que le framework) */
@layer application {
  /* Surcharges spécifiques à l'application */
  .btn-primary {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border: none;

    &:hover:not(:disabled) {
      background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
    }
  }

  .card {
    backdrop-filter: blur(10px);
    background: rgba(255, 255, 255, 0.9);
  }
}

/* Utilitaires - priorité la plus élevée */
@layer utilities {
  /* Classes utilitaires avec la priorité la plus élevée */
  .text-left { text-align: left !important; }
  .text-center { text-align: center !important; }
  .text-right { text-align: right !important; }

  .d-none { display: none !important; }
  .d-block { display: block !important; }
  .d-flex { display: flex !important; }
  .d-grid { display: grid !important; }

  .m-0 { margin: 0 !important; }
  .m-1 { margin: 0.25rem !important; }
  .m-2 { margin: 0.5rem !important; }
  .m-3 { margin: 1rem !important; }
  .m-4 { margin: 1.5rem !important; }
  .m-5 { margin: 3rem !important; }

  .p-0 { padding: 0 !important; }
  .p-1 { padding: 0.25rem !important; }
  .p-2 { padding: 0.5rem !important; }
  .p-3 { padding: 1rem !important; }
  .p-4 { padding: 1.5rem !important; }
  .p-5 { padding: 3rem !important; }

  /* Utilitaires réactifs */
  @media (min-width: 768px) {
    .md\:text-left { text-align: left !important; }
    .md\:text-center { text-align: center !important; }
    .md\:text-right { text-align: right !important; }

    .md\:d-none { display: none !important; }
    .md\:d-block { display: block !important; }
    .md\:d-flex { display: flex !important; }
  }

  @media (min-width: 1024px) {
    .lg\:text-left { text-align: left !important; }
    .lg\:text-center { text-align: center !important; }
    .lg\:text-right { text-align: right !important; }

    .lg\:d-none { display: none !important; }
    .lg\:d-block { display: block !important; }
    .lg\:d-flex { display: flex !important; }
  }
}

Les couches imbriquées se rangent dans l'ordre à l'intérieur de leur parent, et tout le framework occupe une seule place dans la hiérarchie de la page. Depuis l'extérieur, tu désignes une couche interne avec une notation à point, par exemple @layer framework.reset.

2. Couches conditionnelles

À l'intérieur d'une couche, tu peux utiliser @media, @supports et @container, ainsi que des variables CSS pour les thèmes :

/* Couches avec media queries */
@layer responsive {
  @media (max-width: 767px) {
    .mobile-only {
      display: block;
    }

    .desktop-only {
      display: none;
    }

    .container {
      padding: 0 1rem;
    }

    .grid {
      grid-template-columns: 1fr;
    }
  }

  @media (min-width: 768px) {
    .mobile-only {
      display: none;
    }

    .desktop-only {
      display: block;
    }

    .container {
      padding: 0 2rem;
    }
  }
}

/* Couches avec feature queries */
@layer modern {
  @supports (display: grid) {
    .grid-layout {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
      gap: 1rem;
    }
  }

  @supports not (display: grid) {
    .grid-layout {
      display: flex;
      flex-wrap: wrap;
      gap: 1rem;
    }

    .grid-layout > * {
      flex: 1 1 250px;
    }
  }

  @supports (container-type: inline-size) {
    .responsive-component {
      container-type: inline-size;
    }

    @container (min-width: 400px) {
      .responsive-component .card {
        display: flex;
        align-items: center;
        gap: 1rem;
      }
    }
  }
}

/* Couches de thème */
@layer themes {
  [data-theme="light"] {
    --bg-primary: #ffffff;
    --bg-secondary: #f8f9fa;
    --text-primary: #212529;
    --text-secondary: #6c757d;
    --border-color: #dee2e6;
  }

  [data-theme="dark"] {
    --bg-primary: #1a1a1a;
    --bg-secondary: #2d2d2d;
    --text-primary: #ffffff;
    --text-secondary: #b0b0b0;
    --border-color: #404040;
  }

  [data-theme="blue"] {
    --bg-primary: #0f1419;
    --bg-secondary: #1e2a35;
    --text-primary: #ffffff;
    --text-secondary: #8fa3b0;
    --border-color: #2a3f50;
  }
}

La condition décide seulement si les règles s'appliquent. La position de la couche dans la hiérarchie reste la même, quelle que soit la largeur de l'écran ou la prise en charge du navigateur.

Applications pratiques des Cascade Layers

1. Architecture CSS dans les grands projets

Voici à quoi peut ressembler l'architecture complète d'un grand projet avec sept couches. Le bloc est long, alors considère-le comme une carte à parcourir, et non comme un texte à apprendre par cœur :

/* Définition de l'architecture principale */
@layer normalize, base, layout, components, pages, themes, utilities;

/* 1. Normalize/Reset */
@layer normalize {
  /*! normalize.css v8.0.1 | MIT License | github.com/necolas/normalize.css */

  html {
    line-height: 1.15;
    -webkit-text-size-adjust: 100%;
  }

  body {
    margin: 0;
  }

  main {
    display: block;
  }

  h1 {
    font-size: 2em;
    margin: 0.67em 0;
  }

  /* ... reste de normalize.css ... */
}

/* 2. Styles de base */
@layer base {
  :root {
    /* Design tokens */
    --font-family-base: 'Inter', system-ui, sans-serif;
    --font-family-mono: 'JetBrains Mono', 'Fira Code', monospace;

    --font-size-xs: 0.75rem;
    --font-size-sm: 0.875rem;
    --font-size-base: 1rem;
    --font-size-lg: 1.125rem;
    --font-size-xl: 1.25rem;
    --font-size-2xl: 1.5rem;
    --font-size-3xl: 1.875rem;
    --font-size-4xl: 2.25rem;

    --color-primary: #007bff;
    --color-secondary: #6c757d;
    --color-success: #28a745;
    --color-warning: #ffc107;
    --color-danger: #dc3545;
    --color-info: #17a2b8;

    --spacing-xs: 0.25rem;
    --spacing-sm: 0.5rem;
    --spacing-md: 1rem;
    --spacing-lg: 1.5rem;
    --spacing-xl: 2rem;
    --spacing-2xl: 2.5rem;
    --spacing-3xl: 3rem;

    --border-radius-sm: 4px;
    --border-radius-md: 8px;
    --border-radius-lg: 12px;
    --border-radius-xl: 16px;
    --border-radius-full: 50%;

    --shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.1);
    --shadow-md: 0 4px 6px rgba(0, 0, 0, 0.1);
    --shadow-lg: 0 10px 25px rgba(0, 0, 0, 0.15);
  }

  body {
    font-family: var(--font-family-base);
    font-size: var(--font-size-base);
    line-height: 1.6;
    color: var(--text-primary, #212529);
    background: var(--bg-primary, #ffffff);
  }

  h1, h2, h3, h4, h5, h6 {
    margin-top: 0;
    margin-bottom: var(--spacing-md);
    font-weight: 600;
    line-height: 1.2;
    color: var(--text-primary, #212529);
  }

  p {
    margin-top: 0;
    margin-bottom: var(--spacing-md);
    color: var(--text-secondary, #6c757d);
  }

  a {
    color: var(--color-primary);
    text-decoration: none;

    &:hover {
      text-decoration: underline;
    }
  }

  img, svg {
    display: block;
    max-width: 100%;
    height: auto;
  }

  code {
    font-family: var(--font-family-mono);
    font-size: 0.9em;
    background: rgba(0, 0, 0, 0.1);
    padding: 0.2em 0.4em;
    border-radius: var(--border-radius-sm);
  }
}

/* 3. Motifs de mise en page */
@layer layout {
  .container {
    width: 100%;
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 var(--spacing-md);
  }

  .container-fluid {
    width: 100%;
    padding: 0 var(--spacing-md);
  }

  .row {
    display: flex;
    flex-wrap: wrap;
    margin: 0 calc(var(--spacing-md) * -0.5);
  }

  .col {
    flex: 1;
    padding: 0 calc(var(--spacing-md) * 0.5);
  }

  .grid {
    display: grid;
    gap: var(--spacing-md);
  }

  .grid-auto {
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  }

  .flex {
    display: flex;
  }

  .flex-column {
    flex-direction: column;
  }

  .items-center {
    align-items: center;
  }

  .justify-center {
    justify-content: center;
  }

  .justify-between {
    justify-content: space-between;
  }

  .gap-sm { gap: var(--spacing-sm); }
  .gap-md { gap: var(--spacing-md); }
  .gap-lg { gap: var(--spacing-lg); }

  @media (min-width: 768px) {
    .container {
      padding: 0 var(--spacing-lg);
    }

    .grid {
      gap: var(--spacing-lg);
    }

    .md\:flex-row {
      flex-direction: row;
    }

    .md\:gap-xl {
      gap: var(--spacing-xl);
    }
  }

  @media (min-width: 1024px) {
    .container {
      padding: 0 var(--spacing-xl);
    }

    .lg\:grid-cols-3 {
      grid-template-columns: repeat(3, 1fr);
    }

    .lg\:grid-cols-4 {
      grid-template-columns: repeat(4, 1fr);
    }
  }
}

/* 4. Composants réutilisables */
@layer components {
  /* Système de boutons */
  .btn {
    --btn-padding-y: var(--spacing-sm);
    --btn-padding-x: var(--spacing-md);
    --btn-font-size: var(--font-size-base);
    --btn-border-radius: var(--border-radius-md);

    display: inline-flex;
    align-items: center;
    justify-content: center;
    padding: var(--btn-padding-y) var(--btn-padding-x);
    font-size: var(--btn-font-size);
    font-weight: 500;
    border: 1px solid transparent;
    border-radius: var(--btn-border-radius);
    text-decoration: none;
    cursor: pointer;
    transition: all 0.2s ease;
    user-select: none;

    &:focus {
      outline: 2px solid transparent;
      box-shadow: 0 0 0 2px rgba(66, 153, 225, 0.5);
    }

    &:disabled {
      opacity: 0.6;
      cursor: not-allowed;
      pointer-events: none;
    }

    /* Variantes de taille */
    &.btn-sm {
      --btn-padding-y: var(--spacing-xs);
      --btn-padding-x: var(--spacing-sm);
      --btn-font-size: var(--font-size-sm);
    }

    &.btn-lg {
      --btn-padding-y: var(--spacing-md);
      --btn-padding-x: var(--spacing-lg);
      --btn-font-size: var(--font-size-lg);
    }

    /* Variantes de couleur */
    &.btn-primary {
      background: var(--color-primary);
      color: white;
      border-color: var(--color-primary);

      &:hover:not(:disabled) {
        background: color-mix(in srgb, var(--color-primary) 90%, black);
        border-color: color-mix(in srgb, var(--color-primary) 90%, black);
      }
    }

    &.btn-secondary {
      background: var(--color-secondary);
      color: white;
      border-color: var(--color-secondary);

      &:hover:not(:disabled) {
        background: color-mix(in srgb, var(--color-secondary) 90%, black);
        border-color: color-mix(in srgb, var(--color-secondary) 90%, black);
      }
    }

    &.btn-outline {
      background: transparent;
      color: var(--color-primary);
      border-color: var(--color-primary);

      &:hover:not(:disabled) {
        background: var(--color-primary);
        color: white;
      }
    }

    &.btn-ghost {
      background: transparent;
      color: var(--color-primary);
      border-color: transparent;

      &:hover:not(:disabled) {
        background: rgba(var(--color-primary-rgb, 0, 123, 255), 0.1);
      }
    }
  }

  /* Système de cartes */
  .card {
    background: var(--bg-primary, white);
    border: 1px solid var(--border-color, #e9ecef);
    border-radius: var(--border-radius-lg);
    overflow: hidden;
    box-shadow: var(--shadow-sm);
    transition: all 0.3s ease;

    &.card-hover:hover {
      box-shadow: var(--shadow-lg);
      transform: translateY(-2px);
    }

    .card-header {
      padding: var(--spacing-lg);
      border-bottom: 1px solid var(--border-color, #e9ecef);
      background: var(--bg-secondary, #f8f9fa);

      .card-title {
        margin: 0 0 var(--spacing-xs) 0;
        font-size: var(--font-size-lg);
        font-weight: 600;
        color: var(--text-primary);
      }

      .card-subtitle {
        margin: 0;
        font-size: var(--font-size-sm);
        color: var(--text-secondary);
      }
    }

    .card-body {
      padding: var(--spacing-lg);
    }

    .card-footer {
      padding: var(--spacing-md) var(--spacing-lg);
      border-top: 1px solid var(--border-color, #e9ecef);
      background: var(--bg-secondary, #f8f9fa);
    }
  }

  /* Composants de formulaire */
  .form-group {
    margin-bottom: var(--spacing-md);
  }

  .form-label {
    display: block;
    margin-bottom: var(--spacing-xs);
    font-weight: 500;
    color: var(--text-primary);
  }

  .form-control {
    width: 100%;
    padding: var(--spacing-sm) var(--spacing-md);
    font-size: var(--font-size-base);
    border: 1px solid var(--border-color, #ced4da);
    border-radius: var(--border-radius-md);
    background: var(--bg-primary, white);
    color: var(--text-primary);
    transition: all 0.2s ease;

    &:focus {
      outline: none;
      border-color: var(--color-primary);
      box-shadow: 0 0 0 2px rgba(var(--color-primary-rgb, 0, 123, 255), 0.25);
    }

    &::placeholder {
      color: var(--text-muted, #adb5bd);
    }

    &:disabled {
      background: var(--bg-secondary, #f8f9fa);
      opacity: 0.6;
      cursor: not-allowed;
    }
  }

  textarea.form-control {
    resize: vertical;
    min-height: 100px;
  }

  .form-text {
    margin-top: var(--spacing-xs);
    font-size: var(--font-size-sm);
    color: var(--text-muted, #6c757d);
  }

  .form-error {
    margin-top: var(--spacing-xs);
    font-size: var(--font-size-sm);
    color: var(--color-danger);
  }
}

/* 5. Styles spécifiques aux pages */
@layer pages {
  .page-home {
    .hero {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      padding: var(--spacing-3xl) 0;
      text-align: center;

      .hero-title {
        font-size: var(--font-size-4xl);
        margin-bottom: var(--spacing-md);
      }

      .hero-subtitle {
        font-size: var(--font-size-xl);
        opacity: 0.9;
        margin-bottom: var(--spacing-xl);
      }
    }

    .features {
      padding: var(--spacing-3xl) 0;

      .feature-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
        gap: var(--spacing-xl);
      }

      .feature-card {
        text-align: center;
        padding: var(--spacing-lg);

        .feature-icon {
          width: 60px;
          height: 60px;
          margin: 0 auto var(--spacing-md);
          background: var(--color-primary);
          border-radius: var(--border-radius-full);
          display: flex;
          align-items: center;
          justify-content: center;
          color: white;
          font-size: var(--font-size-xl);
        }

        .feature-title {
          font-size: var(--font-size-lg);
          margin-bottom: var(--spacing-sm);
        }

        .feature-description {
          color: var(--text-secondary);
        }
      }
    }
  }

  .page-about {
    .team-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
      gap: var(--spacing-lg);
    }

    .team-member {
      text-align: center;

      .member-avatar {
        width: 150px;
        height: 150px;
        border-radius: var(--border-radius-full);
        margin: 0 auto var(--spacing-md);
        object-fit: cover;
      }

      .member-name {
        font-size: var(--font-size-lg);
        margin-bottom: var(--spacing-xs);
      }

      .member-role {
        color: var(--color-primary);
        font-weight: 500;
        margin-bottom: var(--spacing-sm);
      }

      .member-bio {
        color: var(--text-secondary);
        font-size: var(--font-size-sm);
      }
    }
  }
}

/* 6. Surcharges de thème */
@layer themes {
  /* Thème clair (par défaut) */
  :root,
  [data-theme="light"] {
    --bg-primary: #ffffff;
    --bg-secondary: #f8f9fa;
    --text-primary: #212529;
    --text-secondary: #6c757d;
    --text-muted: #adb5bd;
    --border-color: #dee2e6;
    --color-primary-rgb: 0, 123, 255;
  }

  /* Thème sombre */
  [data-theme="dark"] {
    --bg-primary: #1a1a1a;
    --bg-secondary: #2d2d2d;
    --text-primary: #ffffff;
    --text-secondary: #b0b0b0;
    --text-muted: #6c757d;
    --border-color: #404040;

    .card {
      background: rgba(255, 255, 255, 0.05);
      backdrop-filter: blur(10px);
    }

    .form-control {
      background: var(--bg-secondary);
      border-color: var(--border-color);

      &:focus {
        background: var(--bg-primary);
      }
    }
  }

  /* Thème bleu */
  [data-theme="blue"] {
    --bg-primary: #0f1419;
    --bg-secondary: #1e2a35;
    --text-primary: #ffffff;
    --text-secondary: #8fa3b0;
    --text-muted: #6c7b7f;
    --border-color: #2a3f50;
    --color-primary: #4fc3f7;
    --color-primary-rgb: 79, 195, 247;
  }

  /* Préférence système */
  @media (prefers-color-scheme: dark) {
    :root:not([data-theme]) {
      --bg-primary: #1a1a1a;
      --bg-secondary: #2d2d2d;
      --text-primary: #ffffff;
      --text-secondary: #b0b0b0;
      --text-muted: #6c757d;
      --border-color: #404040;
    }
  }
}

/* 7. Classes utilitaires - priorité la plus élevée */
@layer utilities {
  /* Display */
  .d-none { display: none !important; }
  .d-block { display: block !important; }
  .d-inline { display: inline !important; }
  .d-inline-block { display: inline-block !important; }
  .d-flex { display: flex !important; }
  .d-grid { display: grid !important; }

  /* Positionnement */
  .position-relative { position: relative !important; }
  .position-absolute { position: absolute !important; }
  .position-fixed { position: fixed !important; }
  .position-sticky { position: sticky !important; }

  /* Alignement du texte */
  .text-left { text-align: left !important; }
  .text-center { text-align: center !important; }
  .text-right { text-align: right !important; }
  .text-justify { text-align: justify !important; }

  /* Graisses de police */
  .fw-normal { font-weight: 400 !important; }
  .fw-medium { font-weight: 500 !important; }
  .fw-semibold { font-weight: 600 !important; }
  .fw-bold { font-weight: 700 !important; }

  /* Couleurs */
  .text-primary { color: var(--color-primary) !important; }
  .text-secondary { color: var(--text-secondary) !important; }
  .text-muted { color: var(--text-muted) !important; }
  .text-success { color: var(--color-success) !important; }
  .text-warning { color: var(--color-warning) !important; }
  .text-danger { color: var(--color-danger) !important; }

  /* Couleurs d'arrière-plan */
  .bg-primary { background-color: var(--color-primary) !important; }
  .bg-secondary { background-color: var(--bg-secondary) !important; }
  .bg-success { background-color: var(--color-success) !important; }
  .bg-warning { background-color: var(--color-warning) !important; }
  .bg-danger { background-color: var(--color-danger) !important; }

  /* Utilitaires d'espacement */
  .m-0 { margin: 0 !important; }
  .m-1 { margin: var(--spacing-xs) !important; }
  .m-2 { margin: var(--spacing-sm) !important; }
  .m-3 { margin: var(--spacing-md) !important; }
  .m-4 { margin: var(--spacing-lg) !important; }
  .m-5 { margin: var(--spacing-xl) !important; }

  .p-0 { padding: 0 !important; }
  .p-1 { padding: var(--spacing-xs) !important; }
  .p-2 { padding: var(--spacing-sm) !important; }
  .p-3 { padding: var(--spacing-md) !important; }
  .p-4 { padding: var(--spacing-lg) !important; }
  .p-5 { padding: var(--spacing-xl) !important; }

  /* Marge/padding directionnels */
  .mt-0 { margin-top: 0 !important; }
  .mt-1 { margin-top: var(--spacing-xs) !important; }
  .mt-2 { margin-top: var(--spacing-sm) !important; }
  .mt-3 { margin-top: var(--spacing-md) !important; }
  .mt-4 { margin-top: var(--spacing-lg) !important; }
  .mt-5 { margin-top: var(--spacing-xl) !important; }

  .mb-0 { margin-bottom: 0 !important; }
  .mb-1 { margin-bottom: var(--spacing-xs) !important; }
  .mb-2 { margin-bottom: var(--spacing-sm) !important; }
  .mb-3 { margin-bottom: var(--spacing-md) !important; }
  .mb-4 { margin-bottom: var(--spacing-lg) !important; }
  .mb-5 { margin-bottom: var(--spacing-xl) !important; }

  .pt-0 { padding-top: 0 !important; }
  .pt-1 { padding-top: var(--spacing-xs) !important; }
  .pt-2 { padding-top: var(--spacing-sm) !important; }
  .pt-3 { padding-top: var(--spacing-md) !important; }
  .pt-4 { padding-top: var(--spacing-lg) !important; }
  .pt-5 { padding-top: var(--spacing-xl) !important; }

  .pb-0 { padding-bottom: 0 !important; }
  .pb-1 { padding-bottom: var(--spacing-xs) !important; }
  .pb-2 { padding-bottom: var(--spacing-sm) !important; }
  .pb-3 { padding-bottom: var(--spacing-md) !important; }
  .pb-4 { padding-bottom: var(--spacing-lg) !important; }
  .pb-5 { padding-bottom: var(--spacing-xl) !important; }

  /* Utilitaires réactifs */
  @media (min-width: 768px) {
    .md\:d-none { display: none !important; }
    .md\:d-block { display: block !important; }
    .md\:d-flex { display: flex !important; }
    .md\:text-left { text-align: left !important; }
    .md\:text-center { text-align: center !important; }
    .md\:text-right { text-align: right !important; }
  }

  @media (min-width: 1024px) {
    .lg\:d-none { display: none !important; }
    .lg\:d-block { display: block !important; }
    .lg\:d-flex { display: flex !important; }
    .lg\:text-left { text-align: left !important; }
    .lg\:text-center { text-align: center !important; }
    .lg\:text-right { text-align: right !important; }
  }
}

Chaque couche a une seule mission : pages se place au-dessus des composants, themes au-dessus des pages, et utilities tout en haut, car une classe utilitaire doit toujours l'emporter.

2. Intégration avec les frameworks CSS

Les couches résolvent le problème du début de la leçon. Tu places le code du framework dans les couches inférieures, et tes propres composants dans les couches supérieures :

/* Intégration avec Tailwind CSS */
@layer tailwind-base, components, tailwind-utilities;

@layer tailwind-base {
  /* Styles de base de Tailwind */
  @tailwind base;
}

@layer components {
  /* Composants personnalisés au-dessus de la base de Tailwind */
  .btn-custom {
    @apply px-4 py-2 bg-blue-500 text-white rounded-lg;

    &:hover {
      @apply bg-blue-600;
    }
  }

  .card-custom {
    @apply bg-white shadow-lg rounded-xl p-6;

    .card-title {
      @apply text-xl font-semibold mb-2;
    }

    .card-content {
      @apply text-gray-600 leading-relaxed;
    }
  }
}

@layer tailwind-utilities {
  /* Les utilitaires de Tailwind ont la priorité la plus élevée */
  @tailwind utilities;
}

/* Intégration avec Bootstrap */
@layer bootstrap-reboot, bootstrap-grid, components, bootstrap-utilities;

@layer bootstrap-reboot {
  /* Styles reboot de Bootstrap */
}

@layer bootstrap-grid {
  /* Système de grille de Bootstrap */
  .container {
    width: 100%;
    padding-right: 15px;
    padding-left: 15px;
    margin-right: auto;
    margin-left: auto;
  }

  .row {
    display: flex;
    flex-wrap: wrap;
    margin-right: -15px;
    margin-left: -15px;
  }

  .col {
    flex: 1 0 0%;
    padding-right: 15px;
    padding-left: 15px;
  }
}

@layer components {
  /* Composants personnalisés qui enrichissent Bootstrap */
  .btn-gradient {
    background: linear-gradient(45deg, #007bff, #0056b3);
    border: none;

    &:hover {
      background: linear-gradient(45deg, #0056b3, #004085);
    }
  }

  .card-modern {
    backdrop-filter: blur(10px);
    background: rgba(255, 255, 255, 0.9);
    border: 1px solid rgba(255, 255, 255, 0.2);
  }
}

@layer bootstrap-utilities {
  /* Classes utilitaires de Bootstrap */
}

L'exemple avec Tailwind est une ébauche pour la version 3, dans laquelle les directives @tailwind et @apply sont traitées par Tailwind lui-même. Tailwind 4 range ses styles dans les couches natives theme, base, components et utilities. Tu charges toute une feuille de style externe dans une couche avec l'écriture @import url("bootstrap.css") layer(bootstrap).

Bonnes pratiques des Cascade Layers

1. Stratégie de nommage et d'organisation

Le nom d'une couche doit indiquer le rôle des styles qu'elle contient. Compare les bons et les mauvais noms :

/* Bien - hiérarchie logique des couches */
@layer
  reset,           /* Styles reset/normalize */
  base,            /* Typographie et éléments de base */
  layout,          /* Motifs de mise en page et systèmes de grille */
  components,      /* Composants UI réutilisables */
  pages,           /* Styles spécifiques aux pages */
  themes,          /* Variations de thème */
  utilities;       /* Classes utilitaires */

/* Bien - noms de couches fonctionnels */
@layer
  normalize,
  design-tokens,
  typography,
  forms,
  navigation,
  content,
  interactions,
  responsive,
  print;

/* Mauvais - noms de couches peu clairs */
@layer layer1, layer2, layer3, misc, other;

Des noms comme layer1 ou misc ne veulent plus rien dire au bout d'un mois. Choisis un schéma et tiens-t'y dans tout le projet.

2. Gestion des priorités

Les couches remplacent la plupart des !important, car la priorité découle de l'ordre des couches, et non des points d'exclamation :

/* Bien - gestion explicite des priorités */
@layer framework, custom, overrides;

@layer framework {
  /* Code du framework CSS */
  .button {
    padding: 0.5rem 1rem;
    background: #007bff;
    color: white;
  }
}

@layer custom {
  /* Personnalisations spécifiques au projet */
  .button {
    border-radius: 8px;
    font-weight: 500;
  }
}

@layer overrides {
  /* Surcharges critiques */
  .button.important {
    background: #dc3545 !important;
  }
}

/* Mauvais - s'appuyer uniquement sur !important */
.button {
  background: #007bff !important;
  padding: 0.5rem 1rem !important;
  color: white !important;
}

Attention au piège : !important inverse l'ordre des couches. Une déclaration importante de la couche framework l'emporterait sur une déclaration importante de overrides, et les déclarations importantes dans les couches battent les déclarations importantes situées hors des couches. C'est pourquoi tu dois réserver !important dans les couches à des cas vraiment exceptionnels.

3. Débogage et développement

Pendant le travail, tu peux ajouter des couches d'aide, et même déclarer des couches à l'intérieur de media queries :

/* Aide au débogage des couches */
@layer debug {
  [data-debug="layers"] * {
    position: relative;
  }

  [data-debug="layers"] *::before {
    content: attr(data-layer, 'unknown');
    position: absolute;
    top: 0;
    right: 0;
    background: rgba(255, 0, 0, 0.8);
    color: white;
    font-size: 10px;
    padding: 2px 4px;
    pointer-events: none;
    z-index: 9999;
  }
}

/* Couches pour différents environnements */
@layer development {
  /* Styles réservés au développement */
  .debug-grid {
    background-image:
      linear-gradient(rgba(255,0,0,0.1) 1px, transparent 1px),
      linear-gradient(90deg, rgba(255,0,0,0.1) 1px, transparent 1px);
    background-size: 20px 20px;
  }

  .debug-info {
    position: fixed;
    bottom: 10px;
    right: 10px;
    background: rgba(0, 0, 0, 0.8);
    color: white;
    padding: 10px;
    font-family: monospace;
    font-size: 12px;
    border-radius: 4px;
    z-index: 9999;
  }
}

/* Chargement conditionnel de couches */
@media (max-width: 767px) {
  @layer mobile-specific {
    .desktop-only {
      display: none !important;
    }

    .mobile-nav {
      display: block;
    }
  }
}

@media print {
  @layer print {
    * {
      background: transparent !important;
      color: black !important;
      box-shadow: none !important;
    }

    .no-print {
      display: none !important;
    }
  }
}

Les outils de développement du navigateur affichent le nom de la couche à côté des règles, tu vérifieras donc facilement laquelle l'a emporté.

Les CSS Cascade Layers changent fondamentalement la façon dont le CSS est géré dans les grands projets, en offrant un contrôle précis sur l'ordre d'application des styles et en éliminant le besoin d'utiliser !important dans la plupart des cas. Elles fonctionnent dans tous les principaux navigateurs depuis 2022. Dans le bac à sable ci-dessous, décommente la déclaration @layer reset, base, components, utilities et observe quelle règle l'emporte.

Souviens-toi : les couches sont les étages d'une pyramide, car ce qui se voit au sommet dépend de l'étage, et non du poids d'une seule pierre.

Code de cette leçon : index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Cascade Layers @layer</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="container">
        <h1>Cascade Layers</h1>
        <button class="btn">Bouton de base</button>
        <button class="btn btn-primary">Bouton principal</button>
        <button class="btn btn-gold">Bouton doré</button>
        <p class="info">Les couches contrôlent la priorité du CSS sans !important.</p>
    </div>
</body>
</html>

Entrées de la documentation utilisées dans cette leçon

Tu as repéré une erreur dans cette leçon ?

Teste tes connaissances

Réponds aux questions de cette leçon. Choisis une réponse pour voir tout de suite si elle est correcte.

  1. 1. À quoi sert @layer en CSS ?

Tâches pratiques dans le jeu

  • Éditeur de code

    Crée des cascade layers : @layer reset, base, components, utilities et observe comment elles contrôlent la priorité de la cascade.

  • Tri vertical

    Ordonne les couches @layer de la priorité la plus faible à la plus forte :

  • Clique dans l'ordre

    Ordonne la syntaxe d'une déclaration Cascade Layers :

  1. QuestionLa règle @layer dans la cascade CSS
  2. Exercice de codeCascade Layers avec @layer
  3. Remets dans l'ordreL'ordre de priorité des @layer
  4. Clique dans l'ordreConstruire une déclaration @layer

Articles utiles