Kevin LeClair

Showing Text with the :hover Pseudo Class

So you have a nice in your new website but you want text to appear when the user hovers the cursor over it. There is a simple solution to this:

The HTML markup at this point should be:

Screenshot 2015-01-25 16.44.03

And the CSS styling(or something similar depending on your layout style):

Screenshot 2015-01-25 16.46.17

You’ll find at this point that you have a circular div with a picture in it. When you hover over the middle section of the picture your text will appear. However, the text only appears when you hover over a certain section of the picture. We want the text to appear when you hover over ANY section of the

. We can achieve this by adding a line-height to ourselector CSS styling.

Screenshot 2015-01-25 16.52.18

What this does is creates a space above and below the text. Usually you see this CSS property being used to make text easier to read by having extra space between each line. However, here we are setting the line height to an exaggerated size in order for our

element to take up the full size of our .block

Screenshot 2015-01-25 16.56.30

So now our text will appear when we hover over the image with a cursor, but in front of a picture text can be hard to read. If a picture is darker (like the example above) then we must compensate with a lighter colour. But what if we want to use a brighter picture where our colour scheme will no longer work as well? We can simply add some extra CSS styling.

Screenshot 2015-01-25 16.59.36

By changing the background of our

selector to a transparent black colour with the rgba property we can fix the problem of difficult-to-read text over a bright picture.

Our original picture
Our original picture
The :hover effect in action with our new background, thanks to line heights!
The :hover effect in action with our new background, thanks to line heights!

And there you have it! You have a nice

that when hovered over will produce some nice text and a darker background behind it for readability.

There are a few drawbacks to this method. Adding extra text into your

later down the line will be troublesome with line heights set so high. You’ll find that the text will be pushed outside view unless it can fit on a single line. Also, unless you set a specified height and width for your

the font-size and line heights will not be responsive to different sized browsers or mobile screens. I’ll update this tutorial next week when we learn responsive design at HackerYou!

Check out this codepen to see it in action!

Thanks for reading ☺

Posted on March, 12 2015 in General

Leave a Reply

Your email address will not be published. Required fields are marked *