简体   繁体   English

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

[英]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.我有很多表,但它们都有不同的结构:一个有<table><thead><tbody>类型,而其他只有<table><tbody>类型。

And I need to apply css for thead (if it set in table) OR to tbody (it is set always).我需要为thead(如果它在表中设置)或tbody(它总是设置)应用css。 I shouldn't set styles for both of them, only for the first who goes after <table> tag.我不应该为它们设置样式,只为<table>标记之后的第一个设置样式。

So if I have所以如果我有

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

then CSS should be applied only for thead.那么 CSS 应该只适用于 thead。

And vice versa if I have:如果我有,反之亦然:

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

then CSS should be applied for tbody.那么应该为 tbody 应用 CSS。

I wish there was something like 'if thead is set then...'我希望有类似'如果设置了thead然后......'

If that is an option, you could use a hack with :first-child selector.如果这是一个选项,您可以使用带有:first-child选择器的 hack。

For example, you will select either one of them which is the first child of a <table> :例如,您将选择其中一个是<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.在这种情况下,如果存在thead ,则tbody将不是第一个孩子。 Otherwise, if there is no thead , tbody will be the first child.否则,如果没有thead ,则tbody将是第一个孩子。

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM