Search code examples
csssassstylescss-tables

CSS select either <thead> or <tbody> from <table>


I have the following problem. I have plenty of tables, but they all have different structure: one have <table><thead><tbody> type, while the others have <table><tbody> only.

And I need to apply css for thead (if it set in table) OR to tbody (it is set always). I shouldn't set styles for both of them, only for the first who goes after <table> tag.

So if I have

<table>
 <thead>...</thead>
   <tbody>...<tbody>
</table>

then CSS should be applied only for thead.

And vice versa if I have:

<table>
  <tbody>...</tbody>
<table>

then CSS should be applied for tbody.

I wish there was something like 'if thead is set then...'


Solution

  • If that is an option, you could use a hack with :first-child selector.

    For example, you will select either one of them which is the first child of a <table>:

    table > thead:first-child, table > tbody:first-child{
      /* properties here */
    }
    

    In this case, if a thead is present, tbody will not be the first child. Otherwise, if there is no thead, tbody will be the first child.

    See it in action:

    table > thead tr, /* Select the <tr> in a <thead> if present */
    table > tbody:first-child tr:first-child /* Select the first <tr> in a <tbody> when the <thead> is not present */
    {
      font-weight: bold;
      color: blue;
    }
    
    table{
    margin-top:1em;
    border: 1px solid black;
    }
    <table>
      <thead>
        <tr><th>This is a table with header</th></tr>
      </thead>
      <tbody>
        <tr><td>This is the body</td></tr>
      </tbody>
    </table>
    
    <table>
      <tbody>
        <tr><td>This is a table without header</td></tr>
      </tbody>
      <tbody>
        <tr><td>This is the body</td></tr>
      </tbody>
    </table>