html - CSS 斑马条纹特定表 tr :nth-child(even)

标签 html css html-table tablerow

我只想使用斑马条纹选择表格。我不想为此使用 jQuery。

tbody tr:nth-child(even) td, tbody tr.even td {background:#e5ecf9;}

当我将其放入 css 文件时,它会影响调用相同样式表的所有页面上的所有表格。我想做的是有选择地将它应用于特定表。

我已经试过了,但是没用。

// in stylesheet
.zebra_stripe{
    tbody tr:nth-child(even) td, tbody tr.even td {background:#e5ecf9;}    
}

// in html
<table class="zebra_even">
<colgroup>
    <col class="width_10em" />
    <col class="width_15em" />
</colgroup>
<tr>
    <td>Odd row nice and clear.</td>
    <td>Some Stuff</td>
</tr>
<tr>
    <td>Even row nice and clear but it should be shaded.</td>
    <td>Some Stuff</td>
</tr>
</table>

还有这个:

<table>
    <colgroup>
        <col class="width_10em" />
        <col class="width_15em" />
    </colgroup>
    <tbody class="zebra_even">

样式表可以正常工作,因为它正确地格式化了 html 的其他元素。有人可以帮我解决这个问题吗?

最佳答案

您的代码如下所示:

.zebra_stripe{
    tbody tr:nth-child(even) td, tbody tr.even td {background:#e5ecf9;}    
}

这是错误的(很明显,否则你不需要问这个问题),但离得不远。

解决方案是您只需要在现有的 CSS 选择器中包含 .zebra_stripe。 CSS 不支持大括号中的多层选择器,就像你写的那样。 (还有其他方言,如 Less 和 Sass 确实支持这种语法,如果你真的需要它,但在你的情况下,解决方案不需要任何聪明的语法)

.zebra_stripe tbody tr:nth-child(even) td, .zebra_stripe tbody tr.even td {
    background:#e5ecf9;
}

假设您有一个包含 zebra_stripe 类的表:

<table class='zebra_stripe'>
    ....
</table>

没有类的表不会被 strip 化。

顺便说一下,我已经把你的两个选择器都放在那里了,但你不应该同时需要它们。 nth-child() 选择器应该自己完成这个技巧,而不需要 tr.even 替代。 tr.even 在不支持 nth-child() 的浏览器中是需要的(即旧版本的 IE),但在那种情况下,如果你需要支持它们,您可以使用 even 类来完成,而不需要使用 nth-child()

关于html - CSS 斑马条纹特定表 tr :nth-child(even),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12442750/

相关文章:

jquery - Webshims、IE8 和地理定位

html - 将图像与文本对齐

html - 防止一个 DIV 溢出另一个 div?

html - 如何在 Google Chrome 表格的 tbody 元素上放置左滚动条?

html - 更改表格单元格边框的颜色

html - 将YouTube视频嵌入/加载到Lightbox 2中

javascript - 带有喜欢和评论选项的评论框代码

javascript - 禁止加载 HTML 5 视频

javascript - JS 切换动画(animate.css)?

html - 为什么我的直系后代选择器不起作用?