htmlcsshtml-table

Different css for table if table has only one row


I have multiple tables on a website. In case the table has multiple rows, then each cell should be bordered which is solved now with td {border: 1px solid black;}. But if the table only has one single row, I would like to hide the borders or have the border-width be 0.

Without changing the HTML or using JS, is there a way to accomplish this purely with CSS?


Solution

  • Add a selector for a single row.

    table {
      border-collapse: collapse;
    }
    td {
      border: 1px solid black;
    }
    table tbody tr:only-child td { /* The override. */
      border: none;
    }
    <table>
    <tbody>
      <tr><td>1</td><td>2</td><td>3</td></tr>
    </tbody>
    </table>
    <br>
    <table>
    <tbody>
      <tr><td>1</td><td>2</td><td>3</td></tr>
      <tr><td>4</td><td>5</td><td>5</td></tr>
    </tbody>
    </table>