Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading