Apoyar0

Playground de tablas en HTML

Construye datos tabulares con table, caption, th, scope, thead, tbody, tfoot, colgroup, colspan y rowspan mientras ves y copias el resultado.

Preguntar a la IA

Playground de tablas en HTML

Respuesta generada con openai/gpt-5.4-nano. La IA puede cometer errores. Revisa siempre el resultado.
Estado del proyecto web
Fase Tarea Responsable Estado
Planificación Alcance Ana Completado
Investigación Luis Completado
Desarrollo HTML semántico Mei En curso
Accesibilidad Sam Pendiente
Tareas completadas 2 de 4
HTML
<div class="table-wrapper">
  <table class="data-table">
    <caption>Estado del proyecto web</caption>

    <colgroup>
      <col>
      <col>
      <col>
      <col class="highlighted-column">
    </colgroup>

    <thead>
      <tr>
        <th scope="col">Fase</th>
        <th scope="col">Tarea</th>
        <th scope="col">Responsable</th>
        <th scope="col">Estado</th>
      </tr>
    </thead>

    <tbody>
      <tr>
        <th scope="row" rowspan="2">Planificación</th>
        <td>Alcance</td>
        <td>Ana</td>
        <td>Completado</td>
      </tr>
      <tr>
        <td>Investigación</td>
        <td>Luis</td>
        <td>Completado</td>
      </tr>
      <tr>
        <th scope="row" rowspan="2">Desarrollo</th>
        <td>HTML semántico</td>
        <td>Mei</td>
        <td>En curso</td>
      </tr>
      <tr>
        <td>Accesibilidad</td>
        <td>Sam</td>
        <td>Pendiente</td>
      </tr>
    </tbody>

    <tfoot>
      <tr>
        <th colspan="3" scope="row">Tareas completadas</th>
        <td>2 de 4</td>
      </tr>
    </tfoot>
  </table>
</div>
CSS
.table-wrapper {
  overflow-x: auto;
}

.data-table {
  inline-size: 100%;
  border-collapse: collapse;
  color: CanvasText;
}

.data-table caption {
  margin-block-end: 0.75rem;
  font-weight: 700;
  text-align: start;
}

.data-table :is(th, td) {
  padding: 0.75rem 1rem;
  border: 1px solid color-mix(in oklch, CanvasText 24%, transparent);
  text-align: start;
}

.data-table :is(thead, tfoot) {
  background: color-mix(in oklch, Highlight 16%, Canvas);
}

.data-table .highlighted-column {
  background: color-mix(in oklch, Highlight 10%, transparent);
}

.data-table tbody tr:nth-child(even) {
  background: color-mix(in oklch, CanvasText 6%, transparent);
}

Guía educativa de table

Conservar el contexto de cada celda

Una tabla relaciona datos en dos dimensiones. Aprende a identificarla con caption, asociar encabezados y conservar su lectura al desplazarte por una pantalla pequeña.

Modelo mental

El título identifica el conjunto; los encabezados dan significado a cada dato.

  1. caption · conjunto

    Horas del equipo: identifica qué se compara en esta tabla.

  2. th · coordenadas

    Diseño y Horas previstas: la fila y la columna que explican el dato.

  3. td · dato

    2: dos horas previstas para Diseño, no un número aislado.

Conjunto → encabezados → datoEsquema estático de las relaciones del primer ejemplo. La posición y el color ayudan visualmente; el HTML comunica las asociaciones.

Usa table cuando las filas y columnas relacionan datos, como horarios, mediciones o comparativas. Para distribuir tarjetas o maquetar una página, elige Grid o Flexbox. Una tabla de datos conserva su estructura nativa; no necesita role="grid" para parecer una hoja de cálculo.

Tabla simple: caption y scope

Una primera fila y una primera columna de encabezados suelen bastar.

caption se coloca al principio de table e identifica el tema. thead, tbody y tfoot agrupan filas; tr contiene celdas, th nombra encabezados y td contiene datos. Agrupar una fila en thead no convierte sus td en encabezados. tfoot reúne un resumen, no un pie decorativo.

Horas previstas y registradas

Si la tabla no cabe, enfoca esta área y desplázate con las flechas. Tab continúa fuera del área.

Horas del equipo
Trabajo Horas previstas Horas registradas
Diseño 2 1
Código 3 2
Total 5 3
Cada número cruza un encabezado de fila con uno de columna. El resumen suma las dos filas: 5 horas previstas y 3 registradas. Todos los ejemplos conservan un contenedor desplazable con nombre y foco de teclado.
Horas previstas y registradas
<p id="table-guide-simple-hint">Si la tabla no cabe, enfoca esta área y desplázate con las flechas. Tab continúa fuera del área.</p>
<div class="table-guide-simple" role="region" tabindex="0"
     aria-labelledby="table-guide-simple-caption" aria-describedby="table-guide-simple-hint">
  <table>
    <caption id="table-guide-simple-caption">Horas del equipo</caption>
    <thead>
      <tr>
        <th scope="col">Trabajo</th>
        <th scope="col">Horas previstas</th>
        <th scope="col">Horas registradas</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <th scope="row">Diseño</th>
        <td>2</td>
        <td>1</td>
      </tr>
      <tr>
        <th scope="row">Código</th>
        <td>3</td>
        <td>2</td>
      </tr>
    </tbody>
    <tfoot>
      <tr>
        <th scope="row">Total</th>
        <td>5</td>
        <td>3</td>
      </tr>
    </tfoot>
  </table>
</div>
:root {
  color-scheme: light dark;
}

.table-guide-simple {
  max-inline-size: 100%;
  overflow: auto;

  &:focus-visible {
    outline: 3px solid light-dark(oklch(0.46 0.14 261), oklch(0.82 0.18 261));
    outline-offset: 3px;
  }

  table {
    inline-size: 100%;
    min-inline-size: 26rem;
    border-collapse: separate;
    border-spacing: 0;
    background: light-dark(color-mix(in oklch, oklch(0.95 0.008 95) 94%, white), color-mix(in oklch, oklch(0.22 0.024 260) 92%, black));
    color: light-dark(oklch(0.22 0.01 95), oklch(0.95 0.01 95));
    font-size: 1rem;
    line-height: 1.5;
  }

  caption {
    padding-block: 0.75rem;
    font-weight: 800;
    text-align: start;
    overflow-wrap: anywhere;
  }

  th, td {
    padding: 0.75rem;
    border-block-end: 1px solid light-dark(oklch(0.38 0.008 95), oklch(0.78 0.018 260));
    text-align: start;
    vertical-align: top;
    overflow-wrap: anywhere;
  }

  thead th, tfoot th, tfoot td, th[scope="rowgroup"], th[colspan] {
    background: light-dark(color-mix(in oklch, oklch(0.95 0.008 95) 98%, white), color-mix(in oklch, oklch(0.22 0.024 260) 86%, black));
  }

  @media (forced-colors: active) {
    table, th, td {
      background: Canvas;
      color: CanvasText;
    }

    th, td {
      border-color: CanvasText;
    }

    &:focus-visible {
      outline-color: Highlight;
    }
  }
}

scope="col" identifica encabezados de columna; scope="row", los de fila. No sustituyas th por td en negrita. Describe unidades y abreviaturas en el encabezado o en texto cercano. El caption puede seguir visible aunque otra sección de la página ya tenga un título.

Agrupaciones y celdas combinadas

Ocupar varias posiciones y encabezar un grupo son responsabilidades distintas.

colspan y rowspan definen geometría. En este ejemplo, Plazas abarca dos columnas con scope="colgroup" y un colgroup span="2" real. HTML y CSS encabezan dos filas cada uno con scope="rowgroup"; cada curso tiene su propio tbody. Los encabezados de segundo nivel conservan scope="col" o scope="row".

Plazas por curso, sesión y franja

Si la tabla no cabe, enfoca esta área y desplázate con las flechas. Tab continúa fuera del área.

Plazas disponibles por curso
Curso Sesión Plazas
Mañana Tarde
HTML Fundamentos 12 8
Práctica 6 4
CSS Fundamentos 10 6
Práctica 4 2
Lee el primer 12 como HTML → Fundamentos → Plazas → Mañana. Las celdas ocupadas por rowspan no se vuelven a añadir en la fila siguiente. Cada fila efectiva cubre cuatro columnas.
Plazas por curso, sesión y franja
<p id="table-guide-groups-hint">Si la tabla no cabe, enfoca esta área y desplázate con las flechas. Tab continúa fuera del área.</p>
<div class="table-guide-groups" role="region" tabindex="0"
     aria-labelledby="table-guide-groups-caption" aria-describedby="table-guide-groups-hint">
  <table>
    <caption id="table-guide-groups-caption">Plazas disponibles por curso</caption>
    <colgroup span="1"></colgroup>
    <colgroup span="1"></colgroup>
    <colgroup span="2"></colgroup>
    <thead>
      <tr>
        <th rowspan="2" scope="col">Curso</th>
        <th rowspan="2" scope="col">Sesión</th>
        <th colspan="2" scope="colgroup">Plazas</th>
      </tr>
      <tr>
        <th scope="col">Mañana</th>
        <th scope="col">Tarde</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <th rowspan="2" scope="rowgroup">HTML</th>
        <th scope="row">Fundamentos</th>
        <td>12</td>
        <td>8</td>
      </tr>
      <tr>
        <th scope="row">Práctica</th>
        <td>6</td>
        <td>4</td>
      </tr>
    </tbody>
    <tbody>
      <tr>
        <th rowspan="2" scope="rowgroup">CSS</th>
        <th scope="row">Fundamentos</th>
        <td>10</td>
        <td>6</td>
      </tr>
      <tr>
        <th scope="row">Práctica</th>
        <td>4</td>
        <td>2</td>
      </tr>
    </tbody>
  </table>
</div>
:root {
  color-scheme: light dark;
}

.table-guide-groups {
  max-inline-size: 100%;
  overflow: auto;

  &:focus-visible {
    outline: 3px solid light-dark(oklch(0.46 0.14 261), oklch(0.82 0.18 261));
    outline-offset: 3px;
  }

  table {
    inline-size: 100%;
    min-inline-size: 26rem;
    border-collapse: separate;
    border-spacing: 0;
    background: light-dark(color-mix(in oklch, oklch(0.95 0.008 95) 94%, white), color-mix(in oklch, oklch(0.22 0.024 260) 92%, black));
    color: light-dark(oklch(0.22 0.01 95), oklch(0.95 0.01 95));
    font-size: 1rem;
    line-height: 1.5;
  }

  caption {
    padding-block: 0.75rem;
    font-weight: 800;
    text-align: start;
    overflow-wrap: anywhere;
  }

  th, td {
    padding: 0.75rem;
    border-block-end: 1px solid light-dark(oklch(0.38 0.008 95), oklch(0.78 0.018 260));
    text-align: start;
    vertical-align: top;
    overflow-wrap: anywhere;
  }

  thead th, tfoot th, tfoot td, th[scope="rowgroup"], th[colspan] {
    background: light-dark(color-mix(in oklch, oklch(0.95 0.008 95) 98%, white), color-mix(in oklch, oklch(0.22 0.024 260) 86%, black));
  }

  @media (forced-colors: active) {
    table, th, td {
      background: Canvas;
      color: CanvasText;
    }

    th, td {
      border-color: CanvasText;
    }

    &:focus-visible {
      outline-color: Highlight;
    }
  }
}

Combinar celdas no crea por sí solo una asociación accesible. rowgroup debe corresponder al grupo de filas real; colgroup, al de columnas. Un colgroup permite aplicar ciertas propiedades CSS a columnas, pero no reemplaza sus th. Si los grupos complican la lectura, considera varias tablas simples.

Relaciones explícitas con id y headers

Cuando las relaciones son más complejas, declara los encabezados de cada celda.

Aquí una fila interior cambia el día al que se refieren los datos. Cada th tiene un id único en el documento y cada td enumera en headers los IDs de sus tres encabezados, separados por espacios y sin #. Todos deben pertenecer a la misma tabla. Los encabezados de sesión también declaran su contexto.

Plazas por día, sesión y modalidad

Si la tabla no cabe, enfoca esta área y desplázate con las flechas. Tab continúa fuera del área.

Plazas disponibles por día y modalidad
Sesión Online Presencial
Lunes
Fundamentos 12 8
Práctica 11 7
Martes
Fundamentos 10 6
Práctica 9 5
El primer 12 se relaciona explícitamente con Lunes, Fundamentos y Online. Los IDs están aislados de los demás ejemplos. Al reutilizar varias copias de esta receta, cambia todos los IDs y sus referencias.
Plazas por día, sesión y modalidad
<p id="table-guide-headers-hint">Si la tabla no cabe, enfoca esta área y desplázate con las flechas. Tab continúa fuera del área.</p>
<div class="table-guide-headers" role="region" tabindex="0"
     aria-labelledby="table-guide-headers-caption" aria-describedby="table-guide-headers-hint">
  <table>
    <caption id="table-guide-headers-caption">Plazas disponibles por día y modalidad</caption>
    <thead>
      <tr>
        <th id="table-guide-h-session">Sesión</th>
        <th id="table-guide-h-online">Online</th>
        <th id="table-guide-h-room">Presencial</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <th id="table-guide-h-monday" colspan="3">Lunes</th>
      </tr>
      <tr>
        <th id="table-guide-h-monday-basics"
            headers="table-guide-h-monday table-guide-h-session">Fundamentos</th>
        <td headers="table-guide-h-monday table-guide-h-monday-basics table-guide-h-online">12</td>
        <td headers="table-guide-h-monday table-guide-h-monday-basics table-guide-h-room">8</td>
      </tr>
      <tr>
        <th id="table-guide-h-monday-practice"
            headers="table-guide-h-monday table-guide-h-session">Práctica</th>
        <td headers="table-guide-h-monday table-guide-h-monday-practice table-guide-h-online">11</td>
        <td headers="table-guide-h-monday table-guide-h-monday-practice table-guide-h-room">7</td>
      </tr>
    </tbody>
    <tbody>
      <tr>
        <th id="table-guide-h-tuesday" colspan="3">Martes</th>
      </tr>
      <tr>
        <th id="table-guide-h-tuesday-basics"
            headers="table-guide-h-tuesday table-guide-h-session">Fundamentos</th>
        <td headers="table-guide-h-tuesday table-guide-h-tuesday-basics table-guide-h-online">10</td>
        <td headers="table-guide-h-tuesday table-guide-h-tuesday-basics table-guide-h-room">6</td>
      </tr>
      <tr>
        <th id="table-guide-h-tuesday-practice"
            headers="table-guide-h-tuesday table-guide-h-session">Práctica</th>
        <td headers="table-guide-h-tuesday table-guide-h-tuesday-practice table-guide-h-online">9</td>
        <td headers="table-guide-h-tuesday table-guide-h-tuesday-practice table-guide-h-room">5</td>
      </tr>
    </tbody>
  </table>
</div>
:root {
  color-scheme: light dark;
}

.table-guide-headers {
  max-inline-size: 100%;
  overflow: auto;

  &:focus-visible {
    outline: 3px solid light-dark(oklch(0.46 0.14 261), oklch(0.82 0.18 261));
    outline-offset: 3px;
  }

  table {
    inline-size: 100%;
    min-inline-size: 26rem;
    border-collapse: separate;
    border-spacing: 0;
    background: light-dark(color-mix(in oklch, oklch(0.95 0.008 95) 94%, white), color-mix(in oklch, oklch(0.22 0.024 260) 92%, black));
    color: light-dark(oklch(0.22 0.01 95), oklch(0.95 0.01 95));
    font-size: 1rem;
    line-height: 1.5;
  }

  caption {
    padding-block: 0.75rem;
    font-weight: 800;
    text-align: start;
    overflow-wrap: anywhere;
  }

  th, td {
    padding: 0.75rem;
    border-block-end: 1px solid light-dark(oklch(0.38 0.008 95), oklch(0.78 0.018 260));
    text-align: start;
    vertical-align: top;
    overflow-wrap: anywhere;
  }

  thead th, tfoot th, tfoot td, th[scope="rowgroup"], th[colspan] {
    background: light-dark(color-mix(in oklch, oklch(0.95 0.008 95) 98%, white), color-mix(in oklch, oklch(0.22 0.024 260) 86%, black));
  }

  @media (forced-colors: active) {
    table, th, td {
      background: Canvas;
      color: CanvasText;
    }

    th, td {
      border-color: CanvasText;
    }

    &:focus-visible {
      outline-color: Highlight;
    }
  }
}

headers describe relaciones, no un orden de anuncio garantizado. Prueba la navegación de tablas con los lectores y navegadores de tu audiencia. Antes de mantener una matriz compleja, valora separar un día por tabla y repetir encabezados claros; suele ser más fácil de leer y mantener.

Presentación responsive y desplazamiento

La tabla puede necesitar dos dimensiones; el resto de la página debe adaptarse.

El contenedor usa overflow: auto y la tabla conserva un ancho mínimo legible. tabindex="0" permite enfocar el área también en navegadores que no hacen enfocable el scroll automáticamente. role="region", aria-labelledby y aria-describedby identifican el área y su ayuda. Una parada de teclado adicional se justifica aquí por la demostración del scroll.

Scroll local con encabezados sticky

Si la tabla no cabe, enfoca esta área y desplázate con las flechas. Tab continúa fuera del área.

Registro ampliado de horas del equipo
Trabajo Horas previstas Horas registradas
Diseño 2 1
Código 3 2
Diseño 2 1 1
Código 3 1 1
Diseño 4 1 1
Código 5 1 1
Diseño 6 1 1
Código 7 1 1
Total 11 9
En una pantalla estrecha, enfoca el área y usa las flechas para desplazarte. También hay scroll vertical: los encabezados de columna permanecen en el borde superior. Tab permite salir del área; el scroll no depende de arrastrar.
Scroll local con encabezados sticky
<p id="table-guide-responsive-hint">Si la tabla no cabe, enfoca esta área y desplázate con las flechas. Tab continúa fuera del área.</p>
<div class="table-guide-responsive" role="region" tabindex="0"
     aria-labelledby="table-guide-responsive-caption" aria-describedby="table-guide-responsive-hint">
  <table>
    <caption id="table-guide-responsive-caption">Registro ampliado de horas del equipo</caption>
    <thead>
      <tr>
        <th scope="col">Trabajo</th>
        <th scope="col">Horas previstas</th>
        <th scope="col">Horas registradas</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <th scope="row">Diseño</th>
        <td>2</td>
        <td>1</td>
      </tr>
      <tr>
        <th scope="row">Código</th>
        <td>3</td>
        <td>2</td>
      </tr>
      <tr>
        <th scope="row">Diseño 2</th>
        <td>1</td>
        <td>1</td>
      </tr>
      <tr>
        <th scope="row">Código 3</th>
        <td>1</td>
        <td>1</td>
      </tr>
      <tr>
        <th scope="row">Diseño 4</th>
        <td>1</td>
        <td>1</td>
      </tr>
      <tr>
        <th scope="row">Código 5</th>
        <td>1</td>
        <td>1</td>
      </tr>
      <tr>
        <th scope="row">Diseño 6</th>
        <td>1</td>
        <td>1</td>
      </tr>
      <tr>
        <th scope="row">Código 7</th>
        <td>1</td>
        <td>1</td>
      </tr>
    </tbody>
    <tfoot>
      <tr>
        <th scope="row">Total</th>
        <td>11</td>
        <td>9</td>
      </tr>
    </tfoot>
  </table>
</div>
:root {
  color-scheme: light dark;
}

.table-guide-responsive {
  max-inline-size: 100%;
  overflow: auto;
  max-block-size: 18rem;

  &:focus-visible {
    outline: 3px solid light-dark(oklch(0.46 0.14 261), oklch(0.82 0.18 261));
    outline-offset: 3px;
  }

  table {
    inline-size: 100%;
    min-inline-size: 38rem;
    border-collapse: separate;
    border-spacing: 0;
    background: light-dark(color-mix(in oklch, oklch(0.95 0.008 95) 94%, white), color-mix(in oklch, oklch(0.22 0.024 260) 92%, black));
    color: light-dark(oklch(0.22 0.01 95), oklch(0.95 0.01 95));
    font-size: 1rem;
    line-height: 1.5;
  }

  caption {
    padding-block: 0.75rem;
    font-weight: 800;
    text-align: start;
    overflow-wrap: anywhere;
  }

  th, td {
    padding: 0.75rem;
    border-block-end: 1px solid light-dark(oklch(0.38 0.008 95), oklch(0.78 0.018 260));
    text-align: start;
    vertical-align: top;
    overflow-wrap: anywhere;
  }

  thead th, tfoot th, tfoot td, th[scope="rowgroup"], th[colspan] {
    background: light-dark(color-mix(in oklch, oklch(0.95 0.008 95) 98%, white), color-mix(in oklch, oklch(0.22 0.024 260) 86%, black));
  }

  thead th {
    position: sticky;
    inset-block-start: 0;
    z-index: 1;
    background: light-dark(color-mix(in oklch, oklch(0.95 0.008 95) 98%, white), color-mix(in oklch, oklch(0.22 0.024 260) 86%, black));
  }

  @media (forced-colors: active) {
    table, th, td {
      background: Canvas;
      color: CanvasText;
    }

    th, td {
      border-color: CanvasText;
    }

    &:focus-visible {
      outline-color: Highlight;
    }
  }
}

sticky se refiere al contenedor de scroll más cercano. inset-block-start activa el límite y el fondo opaco evita mezclar textos; z-index conserva el encabezado por encima de los datos. Con border-collapse: separate y border-spacing: 0 se mantienen bordes por celda. La altura máxima limita solo este ejemplo largo.

Conserva caption y encabezados también en móvil. No ocultes thead para sustituirlo únicamente por etiquetas generadas con CSS, ni reduzcas la fuente hasta que todo quepa. Una vista en tarjetas puede requerir otra presentación de los datos y pruebas de accesibilidad. table-layout: fixed con ancho definido cambia el reparto de columnas; no resuelve las asociaciones ni evita por sí solo el desbordamiento de contenido.

Errores frecuentes

Revisa estructura, relaciones y acceso al contenido antes de pulir los bordes.

El encabezado solo se distingue por su apariencia

Resultado esperado
Cada dato conserva encabezados reconocibles sin depender de su color o peso.
Causa
Se usan td en negrita, o thead sin celdas th.
Solución
Usa th y scope para relaciones simples; caption identifica el conjunto.

Las combinaciones desplazan los datos

Resultado esperado
Todas las filas cubren la misma cuadrícula y los grupos tienen límites reales.
Causa
Se cuentan otra vez las posiciones ocupadas por rowspan o se confunde span con scope.
Solución
Cuenta posiciones efectivas y alinea tbody/colgroup con rowgroup/colgroup; simplifica si es necesario.

headers apunta a otra tabla o no encuentra el encabezado

Resultado esperado
Cada referencia resuelve a un th de esta tabla.
Causa
IDs repetidos al copiar el ejemplo, un # en headers o referencias sin actualizar.
Solución
Asigna IDs únicos y revisa todos los tokens de headers tras cambiar filas o columnas.

En móvil faltan columnas o no se puede desplazar

Resultado esperado
Todo el contenido se alcanza sin ensanchar la página ni perder el foco.
Causa
overflow: hidden recorta datos, falta acceso por teclado o se han eliminado encabezados.
Solución
Conserva la tabla nativa dentro de un scroll local con nombre, foco visible y ayuda; prueba teclado y zoom.

Soporte y compatibilidad

La disponibilidad de HTML no certifica cómo se anuncia una tabla concreta.

Las tablas HTML son Baseline Widely Available. Caption, encabezados y secciones forman la base; el resultado accesible también depende de las relaciones correctas y de la combinación navegador/tecnología de asistencia. Los ejemplos funcionan sin JavaScript; sticky es una ayuda visual y el scroll sigue disponible si no se aplica.

Comprueba navegación por celdas, encabezados anunciados, texto ampliado, contraste, foco y scroll en los entornos reales. Evita roles que sustituyan la semántica nativa y no uses los atributos obsoletos summary, border, cellpadding o cellspacing como receta moderna: emplea texto visible y CSS.