Html table spanning cols and rows

HTML tables

In the early days of the web tables were a very important part of building layouts.

Later on they were replaced by CSS and its layout capabilities, and today we have powerful tools like CSS Flexbox and CSS Grid to build layouts. Tables are now used just for, guess what, building tables!

The table tag

You define a table using the table tag:

Inside the table we’ll define the data. We reason in terms of rows, which means we add rows into a table (not columns). We’ll define columns inside a row.

Rows

A row is added using the tr tag, and that’s the only thing we can add into a table element:

table>  tr>tr>  tr>tr>  tr>tr> table>

This is a table with 3 rows.

The first row can take the role of the header.

Column headers

The table header contains the name of a column, typically in a bold font.

Think about an Excel / Google Sheets document. The top A-B-C-D. header.

Column headers

We define the header using the th tag:

table>  tr>  th>Column 1th>  th>Column 2th>  th>Column 3th>  tr>  tr>tr>  tr>tr> table>

The table content

The content of the table is defined using td tags, inside the other tr elements:

table>  tr>  th>Column 1th>  th>Column 2th>  th>Column 3th>  tr>  tr>  td>Row 1 Column 1td>  td>Row 1 Column 2td>  td>Row 1 Column 3td>  tr>  tr>  td>Row 2 Column 1td>  td>Row 2 Column 2td>  td>Row 2 Column 3td>  tr> table>

This is how browsers render it, if you don’t add any CSS styling:

No styling

th, td  padding: 10px; border: 1px solid #333; >

makes the table look more like a proper table:

A proper table

Span columns and rows

A row can decide to span over 2 or more columns, using the colspan attribute:

table>  tr>  th>Column 1th>  th>Column 2th>  th>Column 3th>  tr>  tr>  td colspan="2">Row 1 Columns 1-2td>  td>Row 1 Column 3td>  tr>  tr>  td colspan="3">Row 2 Columns 1-3td>  tr> table>

A colspan example

Or it can span over 2 or more rows, using the rowspan attribute:

table>  tr>  th>Column 1th>  th>Column 2th>  th>Column 3th>  tr>  tr>  td colspan="2" rowspan="2">Rows 1-2 Columns 1-2td>  td>Row 1 Column 3td>  tr>  tr>  td>Row 2 Column 3td>  tr> table>

A rowspan example

Row headings

Before I explained how you can have columns headings, using the th tag inside the first tr tag of the table.

You can add a th tag as the first element inside a tr that’s not the first tr of the table, to have row headings:

table>  tr>  th>th>  th>Column 2th>  th>Column 3th>  tr>  tr>  th>Row 1th>  td>Col 2td>  td>Col 3td>  tr>  tr>  th>Row 2th>  td>Col 2td>  td>Col 3td>  tr> table>

Row headings

More tags to organize the table

You can add 3 more tags into a table, to have it more organized.

This is best when using big tables. And to properly define a header and a footer, too.

They wrap the tr tags to clearly define the difference sections of the table. Here’s an example usage:

table>  thead>  tr>  th>th>  th>Column 2th>  th>Column 3th>  tr>  thead>  tbody>  tr>  th>Row 1th>  td>Col 2td>  td>Col 3td>  tr>  tr>  th>Row 2th>  td>Col 2td>  td>Col 3td>  tr>  tbody>  tfoot>  tr>  td>td>  td>Footer of Col 1td>  td>Footer of Col 2td>  tr>  tfoot> table>

thead and tfoot

Table caption

A table should have a caption tag that describes its content. That tag should be put immediately after the opening table tag:

table>  caption>Dogs agecaption>  tr>  th>Dogth>  th>Ageth>  tr>  tr>  td>Rogertd>  td>7td>  tr> table>

Источник

Как объединить ячейки в HTML-таблице горизонтально и вертикально: colspan и rowspan

Как объединить ячейки в HTML-таблице горизонтально

Рассмотрим простой пример HTML-таблицы с двумя строками и двумя столбцами ( четыре ячейки ). Ее HTML-код выглядит следующим образом:

 
содержимоесодержимое
содержимоесодержимое

Далее, если нужно объединить две ячейки в верхней строке, используйте атрибут colspan=» « следующим образом:

 
содержимое
содержимоесодержимое

Ячейка в верхней строке теперь охватывает два столбца. Поскольку она занимает пространство двух ячеек, в первом ряду есть только один элемент td .

Можно осуществить объединение ячеек таблицы HTML в любой ее области с любым количеством столбцов. Одним из наиболее полезных применений объединения ячеек по горизонтали является создание заголовков таблицы. Если таблица имеет n столбцов, поместите атрибут colspan=»n» в первую ячейку верхнего ряда и удалите другие ячейки из этого ряда.

Как объединить ячейки в HTML-таблице по вертикали: rowspan

Как объединить ячейки в HTML-таблице по вертикали: rowspan

Рассмотрим простой пример HTML-таблицы с четырьмя ячейками, разделенными на две строки и два столбца. HTML-код :

 
содержимоесодержимое
содержимоесодержимое

Чтобы осуществить HTML table объединение ячеек по вертикали, добавьте для первой ячейки верхней строки атрибут rowspan=»2″ , а затем удалите одну из ячеек в нижнем ряду. HTML-код теперь будет выглядеть следующим образом:

 
stuffсодержимое
содержимое

Можно комбинировать горизонтальное и вертикальное объединение ячеек в одной таблице, как показано на рисунке слева. Одна ячейка даже может охватывать несколько строк и столбцов, как показано на рисунке справа. HTML-код для каждой таблицы приведен ниже:

Как объединить ячейки в HTML-таблице по вертикали: rowspan - 2

Способы комбинирования rowspan и colspan для создания пользовательских HTML-таблиц с ячейками, которые охватывают несколько строк и столбцов

 
span 3 rows span 3 columns
H T span 2 rows
M L
span 4 columns
span 2 rows and 2 columns T
A
E L B

Использование вертикально объединенных ячеек

Объединение ячеек по вертикали HTML в одном столбце можно использовать, если нужно создать заголовок для группы строк, примыкающих к этому столбцу. Это также может помочь разделить группы строк по типу.

При представлении данных на сайте в табличном формате, чем лучше вы организуете данные по подгруппам, тем проще пользователям анализировать и обрабатывать эти данные. Разделители пространства помогают нам анализировать вещи более эффективно. Также можно использовать для столбцов цветовой код, чтобы их было еще проще визуально идентифицировать:

Источник

HTML Table Colspan & Rowspan

HTML tables can have cells that span over multiple rows and/or columns.

HTML Table — Colspan

To make a cell span over multiple columns, use the colspan attribute:

Example

Note: The value of the colspan attribute represents the number of columns to span.

HTML Table — Rowspan

To make a cell span over multiple rows, use the rowspan attribute:

Example

Note: The value of the rowspan attribute represents the number of rows to span.

HTML Exercises

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Читайте также:  Python functions args kwargs
Оцените статью