Quick Tips

CSS: On hover change another element’s style

Today’s Quick Tip has to do with being able to change the style of an element on the page when you hover over a different element. The following example is going to show how to display a title bar on hover of a thumbnail.

CSS

#thumbnail {
    display: block;

    width: 150px;
    height: 150px;
}

#thumbnail:hover + #title {
    display: block;
}

#title {
    display: none;

    color: #ffffff;
    background-color: #000000;
    text-align: center;

    width: 130px;
    padding: 10px;
}

HTML

<a id="thumbnail" href="#"><img src="http://dummyimage.com/150x150/0066ff/fff"></a>
<div id="title">filename.jpg</div>

View the effect on CodePen.

So how does it work? Let’s start by looking at line 8. The first selector (#thumbnail:hover) indicates on hover of the element with the id of “thumbnail”, the second selector indicates in this scenario the target that you’d like to change the style of. You may’ve noticed the plus symbol between the two selectors, this is called a combinator. There are four different combinators, check out this list to see what each one is used for.

The plus symbol in this example indicates that the target element is adjacent (immediately following) to the source element (hover element). So when you hover over the element with an id of “thumbnail” it will change the style of the adjacent element if it has an id of “title”. For the actual style i’m simply changing between display: none and display: block to show and hide the element.

That’s pretty much the gist of it. If you have any questions or would like to add to the guide feel free to post in the comments below.