Base de conocimientosCentro de exámenes
ESEspañol
Elegir idioma13

CKTIS / CSS

:target-current — el marcador de desplazamiento activo

La pseudoclase :target-current selecciona el marcador activo dentro de un grupo de marcadores de desplazamiento. Permite resaltar el enlace asociado a la posición de desplazamiento actual, en lugar de limitarse al fragmento de la URL.

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

Sintaxis

:target-current

:target-current es una pseudoclase sin argumentos que selecciona el marcador de desplazamiento activo de un grupo. En el ejemplo, scroll-target-group: auto agrupa los enlaces y nav a:target-current aplica estilos al enlace activo.

No la confundas con :target: esta última selecciona el elemento identificado por el fragmento de la URL, no el enlace que conduce a él. Desplazarse manualmente no cambia por sí solo el fragmento de la URL.

Esta función pertenece a un borrador de especificación. El ejemplo requiere una verificación local en el navegador de destino; los enlaces normales siguen siendo la base de la navegación.

Ejemplos

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Highlighting the current scroll marker</title>
  <style>
    nav { scroll-target-group: auto; }
    nav a { color: rgb(0, 0, 0); }
    nav a:target-current { color: rgb(0, 90, 180); }
    #scroller { position: relative; block-size: 8rem; overflow-y: auto; }
    #scroller section { block-size: 100%; }
    h2 { margin: 0; }
  </style>
</head>
<body>
  <nav aria-label="Section markers">
    <a href="#a">Section A</a>
    <a href="#b">Section B</a>
  </nav>
  <div id="scroller" role="region" aria-label="Scrollable sections" tabindex="0">
    <section id="a" aria-labelledby="heading-a"><h2 id="heading-a">Section A</h2></section>
    <section id="b" aria-labelledby="heading-b"><h2 id="heading-b">Section B</h2></section>
  </div>
  <script>
    const scroller = document.getElementById('scroller');
    const links = [...document.querySelectorAll('nav a')];

    async function report(label, expectedLink) {
      // The current marker is updated during rendering, not in the scrollTop setter.
      let current;
      for (let frame = 0; frame < 120; frame++) {
        await new Promise(resolve => requestAnimationFrame(resolve));
        current = links.find(link => link.matches(':target-current'));
        if (current === expectedLink) break;
      }
      console.log(`${label}: ${current ? current.textContent + ', ' + getComputedStyle(current).color : 'no current marker'}`);
    }

    async function run() {
      const syntaxRecognized = CSS.supports('selector(a:target-current)') &&
        CSS.supports('scroll-target-group', 'auto');
      if (!syntaxRecognized) {
        console.log('The browser does not recognize a:target-current or scroll-target-group: auto.');
        window.addEventListener('hashchange', () => {
          console.log(`Fragment: ${location.hash || '(none)'}`);
        });
        return;
      }
      await report('At start', links[0]);
      scroller.scrollTop = scroller.scrollHeight - scroller.clientHeight;
      await report('At end', links[1]);
    }
    run();
  </script>
</body>
</html>

Resultado

At start: Section A, rgb(0, 90, 180)
At end: Section B, rgb(0, 90, 180)

El código mostrado y el resultado declarado se verificaron en un entorno aislado mediante el método registrado en la evidencia de verificación de esta versión exacta.

Fuentes