Reputation: 2463
I need to merge the center cells in an HTML table, but <td colspan="3" rowspan="3"> </td>
not work as expected. The below image shows what happens when I use colspan
and rowspan
- it messes up the table.
How should I merge 9 cells like the above image without using colspan
. I really want to combine table cells so they don't expand. Can I do it using HTML or do I need to use a jQuery solution?
Upvotes: 3
Views: 10013
Reputation: 5585
colspan
is the right thing to do. The problem you're having is that you added more columns than you intended. Every time you use a colspan
of more than 1, you need to knock a corresponding number of <td>
tags off that row. Also, remember that using rowspan
effectively adds a <td>
to every row that the span covers. So when you do a colspan="3" rowspan="3"
then you need to knock 2 cells off the row that contains the spanned cell, and three off the next two rows.
In the case of your 10x10 table with the 3x3 hole in it, you need this
<table>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td colspan="3" rowspan="3"> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
</table>
EDIT
I'm feeling generous and bored, so here's some PHP. You can tweak the spansize and cellMax values and everything should continue working. Rough edges though. I haven't tested every possible way to break it.
<?php
function draw_table_with_hole($rows, $cols, $span_start_row, $span_start_col, $span_rows, $span_cols) {
$spanning = 0;
for ($row = 0; $row < $rows; $row++) {
if (--$spanning > 0) {
$cell = $span_cols;
} else {
$cell = 0;
}
echo "<tr>";
for (; $cell < $cols; $cell++) {
$cell_code = "<td> </td>";
if ($row === $span_start_row && $cell === $span_start_col) {
$cell_code = '<td colspan="' . $span_cols . '" rowspan="' . $span_rows . '."> </td>';
$cell += ($span_cols - 1);
$spanning = $span_rows;
}
echo $cell_code;
}
echo "</tr>";
}
}
?>
<table>
<?php draw_table_with_hole(10, 10, 3, 4, 3, 3); ?>
</table>
Upvotes: 4