Search code examples
htmlcsscss-tables

Easiest way to add row border when there are rowspans present?


I have a table, half of whose cells are rowspan="2" and the other half are not. See the demo.

I want a border between each "actual" row. That means for H1 and H2, it needs to be on every row. But for H3 and H4, it needs to be on every other row.

What's the most elegant way to do this using CSS? I'd prefer not to have to put a classname on every td just to get this working...


Solution

  • just separate your headers from the actual rows using <thead> and <tbody>. then style only the <tbody> rows. of course you can still style the headers, but it's good mark-up to separate the table header from the content.

    <table>
        <thead>
            <tr>
                <th>H1</th>  
                <th>H2</th> 
                <th>H3</th> 
                <th>H4</th>  
            </tr>        
        </thead>
        <tbody>
            <tr>
              <td rowspan="2">1</td>
              <td rowspan="2">2</td>
              <td>3a</td>
              <td>4a</td>
            </tr>
            ...
    
    /* Style in question: */
    tbody tr:nth-child(even) {
        border-bottom: 2px solid #BBB;
    }