Baza wiedzyCentrum egzaminacyjne
PLPolski
Wybierz język13

CKTIS / CSS

Ruch i przewijanie w CSS

Ruch w CSS obejmuje przejścia między stanami, animacje klatek kluczowych oraz efekty powiązane z przewijaniem. Rozróżniaj zmianę wyglądu elementu od zmiany pozycji przewijania i uwzględniaj preferencję ograniczenia ruchu użytkownika.

Wersja: CSS modules; structured CSSWG indexes reconciled with pinned MDN BCD; Chromium 152 scope gate, per-example verification still required

Składnia

.motion {
  transition: transform 200ms ease;
  animation: move 1s linear;
}

@keyframes move {
  from { transform: translateX(0); }
  to { transform: translateX(24px); }
}

.scroll-container {
  scroll-behavior: smooth;
}

@media (prefers-reduced-motion: reduce) { /* reduce non-essential motion */ }

„motion and scrolling” to grupa zagadnień, a nie właściwość CSS. transition opisuje przejście po zmianie wartości właściwości, na przykład po uzyskaniu fokusu. animation wraz z @keyframes definiuje sekwencję wartości i steruje m.in. czasem trwania oraz powtórzeniami. Możliwość płynnej interpolacji zależy od animowanej właściwości i jej wartości.

Przewijanie zmienia widoczny fragment obszaru przewijalnego. scroll-behavior: smooth określa sposób przewijania wywołanego nawigacją lub interfejsami CSSOM; nie steruje bezpośrednio przewijaniem przez użytkownika. Czas i przebieg płynnego przewijania wybiera przeglądarka, która może też zignorować tę właściwość. Nie jest to animacja transform.

W animacjach sterowanych przewijaniem animation-timeline wiąże postęp animacji z linią czasu opartą na postępie przewijania lub na położeniu elementu względem widocznego obszaru przewijania, a nie z upływem czasu. Funkcje scroll() i view() tworzą anonimowe linie czasu; właściwość animation-timeline może też wskazać nazwaną linię czasu dowolnego z tych dwóch typów. Linia czasu scroll() odzwierciedla postęp przewijania kontenera, a linia czasu view() — postęp przechodzenia elementu przez widoczny obszar przewijania kontenera. W obu funkcjach oś określa osobny, opcjonalny parametr. To coś innego niż animacja czasowa jedynie uruchamiana przewinięciem. Specyfikacje robocze nie stanowią gwarancji obsługi w konkretnej przeglądarce.

prefers-reduced-motion: reduce sygnalizuje preferencję ograniczenia zbędnego ruchu; samo zapytanie nie wyłącza efektów autora. W przykładzie ruch jest dodawany wyłącznie dla no-preference, a przycisk pozostaje dostępny z klawiatury. Przed wdrożeniem zweryfikuj oba ustawienia.

Przykłady

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>CSS motion with a stable button target</title>
  <style>
    #motion {
      margin: 1rem;
      padding: 0.5rem 2.25rem 0.5rem 0.75rem;
    }
    #motion > span {
      display: inline-block;
      pointer-events: none;
    }
    @media (prefers-reduced-motion: no-preference) {
      #motion > span { transition: transform 200ms linear; }
      #motion[aria-pressed="true"] > span {
        transform: translateX(24px);
      }
    }
  </style>
</head>
<body>
  <h1>CSS motion with a stable button target</h1>
  <p>Activate the button to shift the label, then activate it again to move the label back. The label stays still when reduced motion is requested.</p>
  <button id="motion" type="button" aria-pressed="false"><span>Shift label</span></button>
  <script>
    const button = document.getElementById('motion');
    const label = button.firstElementChild;
    button.addEventListener('click', () => {
      button.setAttribute('aria-pressed', String(button.getAttribute('aria-pressed') !== 'true'));
    });

    function readShift() {
      // Flush styles and finish any transition before reading its endpoint.
      const animations = label.getAnimations();
      animations.forEach(animation => animation.finish());
      const transform = getComputedStyle(label).transform;
      return transform === 'none' ? 0 : new DOMMatrixReadOnly(transform).m41;
    }

    const motionAllowed = matchMedia('(prefers-reduced-motion: no-preference)').matches;
    const duration = getComputedStyle(label).transitionDuration;
    button.click();
    const shiftOn = readShift();
    const onPassed = button.getAttribute('aria-pressed') === 'true'
      && shiftOn === (motionAllowed ? 24 : 0);
    button.click();
    const shiftOff = readShift();
    const offPassed = button.getAttribute('aria-pressed') === 'false'
      && shiftOff === 0;
    const stableTarget = getComputedStyle(button).transform === 'none'
      && getComputedStyle(label).pointerEvents === 'none';
    const passed = stableTarget && onPassed && offPassed
      && duration === (motionAllowed ? '0.2s' : '0s');
    console.log(passed ? 'Motion check passed: the button toggles and respects reduced motion'
      : 'Motion check failed');
  </script>
</body>
</html>

Wynik

Motion check passed: the button toggles and respects reduced motion

Podany komunikat w konsoli to oczekiwany wynik, gdy wszystkie warunki sprawdzane przez skrypt są spełnione.

Źródła