CSS 从 <table> 中选择 <thead> 或 <tbody>

Aft*_*maz 3 css styles sass css-tables

我有以下问题。我有很多表,但它们都有不同的结构:一个有<table><thead><tbody>类型,而其他只有<table><tbody>类型。

我需要为 thead 应用 css (如果它在表中设置)或 tbody (它始终设置)。我不应该为他们两个设置样式,而只为第一个在<table>标签后面的人设置样式。

所以如果我有

<table>
 <thead>...</thead>
   <tbody>...<tbody>
</table>
Run Code Online (Sandbox Code Playgroud)

那么 CSS 应该只应用于 thead。

反之亦然,如果我有:

<table>
  <tbody>...</tbody>
<table>
Run Code Online (Sandbox Code Playgroud)

那么CSS应该应用于tbody。

我希望有类似“如果设置了那么......”的东西

E. *_*ias 5

如果这是一个选项,您可以使用带有选择器的 hack :first-child

例如,您将选择其中一个作为 a 的第一个子级<table>

table > thead:first-child, table > tbody:first-child{
  /* properties here */
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,如果 athead存在,tbody则不会是第一个孩子。否则,如果没有theadtbody将是第一个孩子。

看看它的实际效果:

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;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

  • 只是希望表格中没有“&lt;caption&gt;”或任何“&lt;colgroup&gt;”元素。 (2认同)