【问题标题】:Hover not working with nth-child悬停不与第 n 个孩子一起工作
【发布时间】:2023-04-02 12:32:01
【问题描述】:

他在探索 CSS 3 的特性时遇到了一些麻烦:

对于一个表格,我制作了这个 CSS:

table.sortable tbody tr td {
    border-bottom:1px solid;
    height: 20px;
}

table.sortable tbody tr:hover {
    background-color:#BCD2E5 !important;
}

table.sortable tbody tr:nth-child(odd) td {
    background-color: #F3FAFF;
}
table.sortable tbody tr:nth-child(even) td {
    background-color: #FFFFFF;
}

table.new{
    background-color: rgb(255, 255, 187);
}

table.reaction{
    background-color: rgb(255, 128, 64);
}

table.send{
    background-color: rgba(154, 211, 109, 0.470588);
}

问题是悬停不起作用,但如果我将第 n 个子选择器注释掉,它确实有效。同样在某些情况下,我必须给一些行不同的背景颜色。这是给用户的,所以他们可以很容易地看到一些东西的状态。因此,如果我将 class="send" 之类的类分配给一行,它必须从类发送中获取背景颜色。

为什么这行不通?!还是我错过了什么!?

【问题讨论】:

  • 你用的是什么浏览器?
  • 你有一个可以复制这个问题的小提琴吗?

标签: css hover css-selectors


【解决方案1】:

您正在将background-colornth-child 行应用到tdtd 上的 background-color 显示在 trbackground-color 上方。

将您的 CSS 更改为以下内容对我有用(从末尾的 nth-child 选择器中删除 td):

table.sortable tbody tr:hover {
    background-color:#BCD2E5 !important;
}

table.sortable tbody tr:nth-child(odd) {
    background-color: #F3FAFF;
}
table.sortable tbody tr:nth-child(even) {
    background-color: #FFFFFF;
}

td 添加到hover 选择器的末尾,如下所示:

table.sortable tbody tr:hover td {
    background-color:#BCD2E5 !important;
}

查看此代码笔:http://codepen.io/keithwyland/pen/woLmh


如果您将hover 选择器移到 CSS 中的nth-child 选择器之后,则不需要!important。所以,像这样:

table.sortable tbody tr:nth-child(odd) {
    background-color: #F3FAFF;
}
table.sortable tbody tr:nth-child(even) {
    background-color: #FFFFFF;
}

table.sortable tbody tr:hover {
    background-color:#BCD2E5;
}

【讨论】:

  • 啊,当然我现在觉得自己很愚蠢,我没看到那是多么出色。谢谢!
  • 不客气。尽量不要觉得自己很愚蠢!实践是我们所有人学习的方式。继续加油!
  • 我刚刚发现是因为浏览器兑现了修改后的 CSS 没有下载。但是直到你指向它,我仍然没有看到 td。
猜你喜欢
  • 1970-01-01
  • 2013-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-22
  • 2017-03-11
  • 1970-01-01
  • 2021-04-05
相关资源
最近更新 更多