Fancy HTML tables with CSS

I got an email from an anonymous reader a few days ago who, after presumably reading my recent article on "pretty tables", wanted to know if there was a way to extend the idea:

Do you know if it's possible to change the background colour of an entire table row on a "mouseover event" without using javascript? I know how to do this using image rollovers and javascript but I'm wandering if there's some way of doing it using CSS instead.

Well miss anonymous, the answer is yes. It is possible. By using a "hover pseudo-class" declaration for the table row and combining it with the "!important" rule, you can get the effect you're after:

KeyValue
ACTAustralian Capital Territory
NSWNew South Wales
NTNorthern Territory
QLDQueensland
SASouth Australia
TASTasmania
VICVictoria
WAWestern Australia

The CSS code you'll need, preferably in a separate file:

table.fancy {
  margin: 1em 1em 1em 0;
  background: whitesmoke;
  border-collapse: collapse;
}
table.fancy tr:hover {
   background: lightsteelblue !important;
}
table.fancy th, table.fancy td {
  border: 1px silver solid;
  padding: 0.2em;
}
table.fancy th {
  background: gainsboro;
  text-align: left;
}
table.fancy caption {
  margin-left: inherit;
  margin-right: inherit;
}

The HTML code is very simple with "fancy" being the only class declaration:

<table class="fancy">
<tr>
<th>Key</th><th>Value</th>
</tr>
<tr>
<td>ACT</td><td>Australian Capital Territory</td>
</tr>
<tr>
<td>NSW</td><td>New South Wales</td>
</tr>
<tr>
<td>NT</td><td>Northern Territory</td>
</tr>
<tr>
<td>QLD</td><td>Queensland</td>
</tr>
<tr>
<td>SA</td><td>South Australia</td>
</tr>
<tr>
<td>TAS</td><td>Tasmania</td>
</tr>
<tr>
<td>VIC</td><td>Victoria</td>
</tr>
<tr>
<td>WA</td><td>Western Australia</td>
</tr>
</table>

If you've read the previous article, you'll notice that both the HTML and the CSS code is identical, except that our new "fancy table" contains one additional declaration:

table.fancy tr:hover {
   background: lightsteelblue !important;
}

Easy, wasn't it? Again, change the colours to suit your own bad taste. Of course, this won't work in MSIE, due to it's buggy CSS behaviour.

Due to the large volume of spam, comments are disabled. If you have anything relevant to say, you can leave a , or contact me directly.

About the author

Ivan's mugshotI'm Ivan Lutrov and I'm the owner of Lutrov Interactive. I have 25 years of experience producing interactive work and I create cost effective business websites that are simple, engaging and easy to use. I practice what I preach and I say what I really think, even if it's sometimes not what you want to hear. Subscribe to the Lutrov Interactive feed via RSS and follow me on Twitter.