CSS Hover Blocks of Text

If you want to create the visual effect of changing the background color on blocks of text when your mouse pointer moves over them, here are two simple solutions. Both methods work in Windows:

  • Firefox 1.5
  • Netscape 7.2
  • Opera 8.5

Unfortunately, for Internet Explorer 6, only the second method works (and not completely without applying a small hack.)

Before we get into the methods themselves, here is the end result:

This is example #1. If your using Internet Explorer, nothing will happen when you mouse over this box. What a bummer. If you have a Mozilla based browser, then you get the effect. You can also put a link in and see how it behaves.

This is example #2. It works swell in all the Windows browsers listed above. That means that you can add this little extra visual zing and even IE users will see it. Oh happy day. You can also put a link in and see how it behaves.

Method #1: CSS pseudo class :hover

The W3C CSS2 recommendation allows for three types of dynamic pseudo-class selectors. They are 1) :hover 2) :active 3) :focus. We will be using the :hover pseudo-class. Those familiar with CSS mostly use this for <a> tags. When you want to change the color, border, font-size, etc. when a link is hovered. Here, we're going to use it on our <p> tag.

HTML
<div id="box">
<p>This is example #1...blah, blah.</p>
</div>

CSS
#box p:hover {
background: #dd0;
}

I've obviously styled the box with a width, background color and borders. But, the magic is in the #box p:hover declaration.

Method #2: DOM Properties & Events

With this method we're going to use the DOM property: className and the DOM events: onmouseover & onmouseout.

HTML
<div id="dom">
<p onmouseover="this.className = 'on'" onmouseout="this.className='off'">This is
example #2...blah, blah.</p>
</div>

CSS
.on {
background: #dd0;
height: 1%; /* Holly Hack */
}

.off {
background: #cc0;
}

The DOM property: className lets us get and set the value of the class attribute of the specified element. In this case, the background color of the <p> tag. We trigger the change of style with the DOM events: onmouseover & onmouseout.

In plain english, we are changing the style of the <p> tag from class="off" to class="on" when we run our mouse pointer over the paragraph.

This is almost good enough to make Internet Explorer do what we want, but not quite. We need to use the Holly Hack of adding width: 1% to the .on class. This fixes a number of weird IE bugs. In this case, it fixes an annoying flicker of the hovered background color when your mouse travels between the lines of text.

That's it! Have fun, and like most neat tricks...don't overuse it.