colspan
and rowspan
are HTML attributes used in table cells (<td>
and <th>
) to make cells span multiple columns or rows. These attributes are useful for creating complex table layouts.
Colspan
colspan
is used to make a cell span across multiple columns.
Example of Colspan
<!DOCTYPE html> <html> <head> <style> table { width: 50%; border-collapse: collapse; } th, td { border: 1px solid black; padding: 8px; text-align: center; } </style> </head> <body> <table> <tr> <th colspan="2">Header 1 and 2</th> <th>Header 3</th> </tr> <tr> <td>Row 1, Cell 1</td> <td>Row 1, Cell 2</td> <td>Row 1, Cell 3</td> </tr> <tr> <td colspan="3">Row 2, spans all columns</td> </tr> </table> </body> </html>
- The first header cell spans across two columns.
- The second row has a cell that spans across all three columns.
Rowspan
rowspan
is used to make a cell span across multiple rows.
<!DOCTYPE html> <html> <head> <style> table { width: 50%; border-collapse: collapse; } th, td { border: 1px solid black; padding: 8px; text-align: center; } </style> </head> <body> <table> <tr> <th>Header 1</th> <th>Header 2</th> <th>Header 3</th> </tr> <tr> <td rowspan="2">Row 1 and 2, Cell 1</td> <td>Row 1, Cell 2</td> <td>Row 1, Cell 3</td> </tr> <tr> <td>Row 2, Cell 2</td> <td>Row 2, Cell 3</td> </tr> </table> </body> </html>
The first cell in the second row spans across two rows.
Combining Colspan and Rowspan
You can also combine both colspan
and rowspan
in a single table:
Example of Combined Colspan and Rowspan
<!DOCTYPE html> <html> <head> <style> table { width: 50%; border-collapse: collapse; } th, td { border: 1px solid black; padding: 8px; text-align: center; } </style> </head> <body> <table> <tr> <th colspan="3">Header spanning 3 columns</th> </tr> <tr> <td rowspan="2">Cell spanning 2 rows</td> <td>Row 1, Cell 2</td> <td>Row 1, Cell 3</td> </tr> <tr> <td colspan="2">Cell spanning 2 columns</td> </tr> </table> </body> </html>
- The first header cell spans across three columns.
- The first cell in the second row spans across two rows.
- The second cell in the third row spans across two columns.
These attributes are useful for creating more complex table layouts and ensuring that your table data is presented clearly.