Use CSS pseudo-class to change another element's styling

If you hover near the image header on this site, another image will pop up on top of it. I thought that would be a neat effect, but I would normally do something like this with a jQuery $(“#id”).hover() type of thing, and this site is probably the only site I’ve done in years that doesn’t load jQuery. jQuery is small and generally everybody has the Google CDN version cached, but I didn’t want to load jQuery just for what is really styling.

Looking for a plain-old JavaScript way to do it, I stumbled onto how to do it in pure CSS.

As it turns out, a CSS pseudo-class is able to effect the styling of descendant (li a) and adjacent (li > a or li + a) selectors. That’s kind of awesome. The structure of the image header is:

1
2
3
4
<div class="logo-image">
<img src="/images/logo.png" width="122" height="122">
<img src="/images/quote.png" width="112" height="28" id="logo-quote">
</div>

I made the outer div :hover pseudo-class change the visibility of the quote, which is otherwise hidden.

1
2
3
4
5
6
7
8
9
.logo-image:hover #logo-quote {
display: inline-block;
}

#logo-quote {
position: absolute;
top: 20px;
left: 50%;
display: none;
}

One downer here - there doesn’t appear to be a way to apply a CSS transition to the display property of an element. It just pops on, which is kinda ugly. To get it to fade in and out, you can modify the element’s opacity rather than its display property.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
.logo-image:hover #logo-quote {
opacity: 1;
}

#logo-quote {
position: absolute;
top: 20px;
left: 50%;
opacity: 0;
-webkit-transition: opacity 0.30s ease-in-out;
-moz-transition: opacity 0.30s ease-in-out;
-ms-transition: opacity 0.30s ease-in-out;
-o-transition: opacity 0.30s ease-in-out;
transition: opacity 0.30s ease-in-out;
}

Now that I know how to do that, there are quite a few things I’ve built over the years that I could have done just with CSS rather than by leveraging JavaScript. The next time a similar problem approaches, I’ll be able to take a different approach.