Tuesday, November 22, 2011

How to make hover effects work in Internet Explorer

Thanks to http://www.bernzilla.com/item.php?id=762 for the post. :)

I spent about an hour this morning trying to figure out how in the world to get IE7 to apply my :hover styling to a non-anchor (<a>) element. Amazingly enough, numerous searches on Google turned up absolutely nothing. I found one forum post that looked promising, but it was one of those depressing forum posts that states the exact same problem you're having, but doesn't have any replies.

What made things more frustrating was that there are blog posts galore touting IE7's addition of support for :hover on all elements, yet no matter what I tried I couldn't get it to work!

Eventually, I recalled reading something on the IEBlog about how a web page's DOCTYPE would dictate the CSS support in IE7. The gist of it is, if you want support for :hover on all elements and not just the <a> tag, make sure you're using a strict DOCTYPE so IE7 doesn't kick in to quirks mode.

Whereas the following HTML resulted in my hover effects working in Firefox but not IE7

<html>
 <head>
  <title>Test</title>
  <style type="text/css">
  <!--
   table { background-color: #DDD; }
   tr:hover { background-color: #000; color: #FFF; }
   p { background-color: #EEE; }
   p:hover { background-color: #CCC; }
  //-->
  </style>
 </head>
 <body>
  <p>
   This is just one of those paragraph things.
  </p>
  <table cellpadding="0" cellspacing="0">
   <tr>
    <td>This here is a table row.</td>
   </tr>
   <tr>
    <td>This is a table row too.</td>
   </tr>
  </table>
 </body>
</html>

...simply adding the HTML 4.01 Strict DOCTYPE to the top of the HTML document made IE7 obey my :hover rules as well:

WORKING CODE

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
 <head>
  <title>Test</title>
  <style type="text/css">
  <!--
   table { background-color: #DDD; }
   tr:hover { background-color: #000; color: #FFF; }
   p { background-color: #EEE; }
   p:hover { background-color: #CCC; }
  //-->
  </style>
 </head>
 <body>
  <p>
   This is just one of those paragraph things.
  </p>
  <table cellpadding="0" cellspacing="0">
   <tr>
    <td>This here is a table row.</td>
   </tr>
   <tr>
    <td>This is a table row too.</td>
   </tr>
  </table>
 </body>
</html>

Internet Explorer 7 and later, in standards-compliant mode (strict !DOCTYPE), can apply the :hover pseudo-class to any element, not merely links.


2 comments:

  1. Even giving the following would work...

    <!DOCTYPE html>

    ReplyDelete
  2. Thx dear friends,

    Your suggestion for hover effect in IE7 relay work.

    Email : ranjanhira@in.com

    ReplyDelete