HTML\CSS: change cell background for hover state with CSS

Moon picture Moon · Sep 21, 2010 · Viewed 14.7k times · Source

look at this jsFIDDLE sample

i want to change the cell background color for hover state with CSS.. it can be attained through JavaScript but i want to do it with CSS... plus i want the whole cell to act as a link how to do it

Answer

RoToRa picture RoToRa · Sep 21, 2010

There are several things you need to take into consideration:

  • Don't mix CSS and presentational HTML otherwise it will get very confusing. Colors (for text, background, borders), sizes, alignment, anything that has to do with the look of the site belong into the CSS.

  • Try to avoid tables for layout purposes. They may seem easier as a beginner, but it's an outdated technique.

  • In the CSS you need to move the :hover rule before :visited rule. Since both rules have the same specificity the first rule (currently :visited) with take preference and visited links will never have the hover rule applied to.

  • You don't need to repeat styles in CSS for every rule. Due to inheritance and cascading many styles are automatically applied to child elements.

  • You need to set the background colors on the links instead of the table cells, then you can change the background color on hover just as you already are with the text color.

  • Giving the links display: block will have the links stretch over the whole width of it's containing block, since that is the default behaviour of block elements.

Here is an example how the same layout with "clean" CSS and HTML should look like:

http://www.jsfiddle.net/QShRF/5/