Search code examples
htmlcsscss-tables

Highlight same nth-child element


Suppose I have the following table:

+----------+
| A  |  B  |
+----------+
| 1  |  2  |
+----------+

I want to make so that when I hover over A that 1 gets certain css styles, ditto for B and 2. Is there a way to do this without using js?

Here's a fiddle to see what I mean


Solution

  • With this markup and pure CSS it's not possible because you would need to use td:hover to apply the CSS rule on mouseover, and there is no selector that lets you travel up the DOM tree (which would be necessary as you want to target cells that live in a different branch from the one being hovered).

    If you can modify then a solution such as Dustin's can work; if you can use JS then it's also a matter of sprinkling a little jQuery on the table:

    $("td").on("mouseenter mouseout", function() {
        var $this = $(this);
        $this.closest("table").find("td:nth-child(" + ($this.index() + 1) + ")")
                              .toggleClass("hover");
    });