html - 在悬停时为 HTML 表格边框着色
问题描述
tr
当我将鼠标悬停在它上面时,我想让它的顶部和底部边框改变颜色。我遇到的问题是tr
上面的悬停样式覆盖了悬停样式(至少这是我认为正在发生的事情)。
在我的示例中,第一个项目正确悬停,但在第二个和第三个项目中,只有底部边框突出显示:
table {
border-collapse: collapse;
}
th {
background-color: rgb(231, 231, 231);
}
td {
border-bottom: 2px solid rgb(214, 214, 214);
border-top: 2px solid rgb(214, 214, 214);
}
table tr:hover td {
border-bottom: 2px solid red;
border-top: 2px solid red;
}
<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>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
</table>
解决方案
如果你想保留你的 2 px 边框,你需要摆脱折叠,然后删除边框填充。然后,您可以使用同级选择器更改悬停时的正确边框。
在下面,我刚刚在您的表格中添加了一个 thead 和 tbody,以便我们知道只有 body 元素在悬停时会发生变化
table {
border-spacing:0;
}
th {
background-color: rgb(231, 231, 231);
}
td {
border-top: 2px solid rgb(214, 214, 214); /* make all cells have a top border */
}
tbody tr:last-child td {
border-bottom: 2px solid rgb(214, 214, 214); /* make the last row also have a bottom border */
}
tbody tr:hover td {
border-color: red; /* change all borders to red on hover (mainly because of the last child bottom border */
}
tbody tr:hover + tr td {
border-top-color: red; /* change any cells without a bottom border - make the next row have top border go red (so it looks like current row bottom border) */
}
<table>
<thead>
<tr>
<th>COMPANY</th>
<th>CONTACT</th>
<th>COUNTRY</th>
</tr>
</thead>
<tbody>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
</tbody>
</table>
推荐阅读
- node.js - 我的 React/Node 应用程序在本地工作,但在 Heroku 上不工作
- jwplayer - Google DFP JW 播放器集成
- firebase - expo 和 firestore,未处理的承诺拒绝:typeError
- c++ - 检查连接状态 - Ignite 的 C++ odbc 驱动程序
- python-3.x - 将一系列矩阵相乘
- wordpress - 在生成下载文件时等待 10 秒 - 他们为什么创建以及从哪里获取这些代码?
- c# - 带有可选查询字符串的 API 正在丢失路由值
- c# - Unity无法旋转粒子系统
- javascript - 不使用 $(document).on 时,jquery touchswipe swipe 功能不起作用
- c++ - 如何使用boost Spirit x3 kleene star?