Home >Web Front-end >CSS Tutorial >How can I highlight both table rows and columns on hover using only CSS?

How can I highlight both table rows and columns on hover using only CSS?

DDD
DDDOriginal
2024-11-07 14:53:03627browse

How can I highlight both table rows and columns on hover using only CSS?

Highlighting Table Rows and Columns on Hover Using CSS "Hover" Pseudoclass

In this scenario, highlighting both the table row and column on hover is possible using semantic elements like and . Let's explore a pure CSS method:

Using Pseudo-Elements for Highlighting

To highlight the row and column, we utilize the ::before and ::after pseudo-elements. These create virtual elements positioned absolutely that exist outside the flow of the document:

td:hover::before, /* Highlight rows on hover */
.row:hover::before { 
    background-color: #ffa;
    content: '<pre class="brush:php;toolbar:false"><tr class="row">
    <th class="col">50kg</th>
    <th class="col">55kg</th>
    <th class="col">60kg</th>
    <th class="col">65kg</th>
    <th class="col">70kg</th>
</tr>
a0'; height: 100%; left: -5000px; position: absolute; top: 0; width: 10000px; z-index: -1; } td:hover::after, /* Highlight columns on hover */ .col:hover::after { background-color: #ffa; content: 'a0'; height: 10000px; left: 0; position: absolute; top: -5000px; width: 100%; z-index: -1; }
  • td or .row being hovered triggers highlighting of the entire row.
  • td or .col being hovered triggers highlighting of the entire column.
  • z-index: -1 places the highlights below table data cells.
  • position: absolute and extremely large dimensions allow highlights to extend beyond cell boundaries.
  • overflow: hidden on the table hides any overflow.

CSS Classes for Specificity

In the HTML, we add classes like .row and .col to specify the target element clearly:

Conclusion

This solution highlights both rows and columns on hover purely using CSS and does not rely on JavaScript or jQuery. It works in all modern browsers and gracefully degrades in older browsers.

The above is the detailed content of How can I highlight both table rows and columns on hover using only CSS?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn