TCB13
TCB13

Reputation: 3155

CSS: :hover on element and target another

let's consider we have the following code:

<div class="post wrapper">
    <div class="post title">
        <h3>Title</h3>
    </div>
    <div class="post thumb"> // This has the post thumb set as background image
        <div class="post overlay"></div>
    </div>
</div>

That with some extra CSS will result in:

enter image description here

If I want to get a nice effect when the user has the mouse the image I can do;

div.post.overlay:hover {
    background-color: rgba(0,0,0,0.2);
}

Now, the :hover effect will not work if the user places the mouse on the Title text / white box. To get around this I'm using:

div.post.wrapper:hover div.post.overlay { // => note where :hover is
    background-color: rgba(0,0,0,0.2);
}

Is this valid CSS? Will it work reliable across browsers? Is it okay to call :hover on the wrapper and then set the background-color on the overlay. It seems to work under Google Chrome and Safari.

Thank you.

Upvotes: 1

Views: 931

Answers (1)

Soolie
Soolie

Reputation: 1820

This is perfectly okay. As long as the div.post.overlay is inside the div.post.wrapper, when you hover over the div.post.wrapper, the div.post.overlay gets the styles applied. This is valid in all browsers and it's a normal descendant selector.

Upvotes: 3

Related Questions