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

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

而且我需要将 css 应用于 thead(如果它在 table 中设置)或应用于 tbody(它始终设置)。我不应该为他们两个都设置 styles ,只为第一个在 <table> 标记之后的人设置。

所以如果我有

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

那么 CSS 应该只适用于 thead。

如果我有,反之亦然:

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

那么 CSS 应该应用于 tbody。

我希望有类似'如果设置了thead然后......'

回答1

如果这是一个选项,您可以使用带有 https://developer.mozilla.org/pt-BR/docs/Web/CSS/:first-child 选择器的 hack。

例如,您将选择其中一个是 <table> 的第一个孩子:

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

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

看看它的实际效果:

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>

相似文章

javascript - table 主体不如 table 宽

我有一个table,其中第一列保持固定。我希望table可以垂直滚动。我想我已经接近了,下面几乎可以满足我的要求,唯一的问题是table行不如列宽,我不确定为什么?.tableth:first-chi...

随机推荐

最新文章