Tables have got to be the most awkward set of elements offered by the HTML spec. Both JavaScript and CSS have their issues in dealing with tables, yet they still remain the most popular way to not only present data, but to render a sites layout.

Without CSS 3 and JavaScript, you can get by using :first-child and sibling selectors to style most basic table structures. But what happens, when attributes such as rowspan are thrown into the mix?

This presents an issue for both :first-child and sibling selectors, as it doesn't always accurately return the first child or sibling on the rendered table.

Take, for example, the following table:

<table>
<tbody>
<tr>
  <td rowspan="2">x</td>
  <td>x</td>
</tr>
<tr>
  <td>x</td>
</tr>
</table>

On the rendered table, tr td:first-child will return the first row and column, but will also select the first-row and column of the second row (visually). :first-child will also select the second row, second column. This presents an issue when we want to use CSS to style our table.

jQuery to the rescue. By using the [rowspan] selector, we can add a class on all table cells that make use of the rowspan attribute:

$('td[rowspan]').addClass('hasRowSpan');

This then makes our CSS a little more flexible:

table tr td.hasRowSpan { }  /* first column (visually) */
table tr td:first-child, table tr td.hasRowSpan + td { } /* second column (visually) */
table tr td:first-child + td + td { } /* third column (visually) */

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *