【问题标题】:Text and background color into a table文本和背景颜色成表格
【发布时间】:2019-04-25 03:21:02
【问题描述】:

我有一个表格,我希望当鼠标悬停在表格上时单元格的内容及其背景会改变颜色。所以我尝试了以下CSS

td {
  background-color: white;
  color: black;
}

td:hover {
  background-color: black;
  color: white;
}
<table width="150px">
  <tr>
    <td><a href="www.testing.com">testing</a></td>
  </tr>
</table>

看似简单,但行不通。背景改变了它的颜色,而文本没有改变。

我的错在哪里?我该如何纠正?

【问题讨论】:

  • 请提供您的html代码。
  • 您的代码工作正常:jsfiddle.net/9tb2L1q0 请您编辑您的问题并使用minimal reproducible example 证明您的问题,因为您可能有其他样式与上述样式冲突
  • 可能是cdn问题。检查here
  • 也添加你的html
  • @Pete 单元格中的文本是一个链接:这里jsfiddle.net/9tb2L1q0/3 有一个问题示例。尝试使用 a:hover 并不好(jsfiddle.net/9tb2L1q0/4),因为字符串只有在完全悬停时才会变成白色。目的是让一个单元格包含一个链接,当鼠标悬停在单元格上时,该链接会漂亮地改变颜色,而不一定是链接。

标签: css html-table colors


【解决方案1】:

好的,链接通常有自己的悬停样式,因此您需要定位表格中的链接以更改其颜色:

td {
  background-color: white;
  color: black;
}

td:hover {
  background-color: black;
  color: white;
}

td:hover a {     /* only target links in a td cell that is hovered */
  color: white;
}
<table width="150px">
  <tr>
    <td><a href="www.testing.com">testing</a></td>
  </tr>
</table>

【讨论】:

    【解决方案2】:

    您发布的 css 并不正确,但可能会被其他内容覆盖。尝试添加重要以查看是否是这种情况:

    你也可以发布你的html吗?

     td {
         background-color: white !important;
         color: black !important;
         }
      td:hover {
         background-color: black !important;
         color: white !important;
         }
    <h2>HTML Table</h2>
    
    <table>
      <tr>
        <th>Company</th>
        <th>Contact</th>
        <th>Country</th>
      </tr>
      <tr>
        <td>Alfreds Futterkiste</td>
        <td>Maria Anders</td>
        <td>Germany</td>
      </tr>
      <tr>
        <td>Centro comercial Moctezuma</td>
        <td>Francisco Chang</td>
        <td>Mexico</td>
      </tr>
      <tr>
        <td>Ernst Handel</td>
        <td>Roland Mendel</td>
        <td>Austria</td>
      </tr>
      <tr>
        <td>Island Trading</td>
        <td>Helen Bennett</td>
        <td>UK</td>
      </tr>
      <tr>
        <td>Laughing Bacchus Winecellars</td>
        <td>Yoshi Tannamuri</td>
        <td>Canada</td>
      </tr>
      <tr>
        <td>Magazzini Alimentari Riuniti</td>
        <td>Giovanni Rovelli</td>
        <td>Italy</td>
      </tr>
    </table>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-25
      • 1970-01-01
      • 2019-08-30
      • 2015-01-01
      • 2018-02-27
      • 1970-01-01
      • 2012-12-21
      • 1970-01-01
      相关资源
      最近更新 更多