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

14,797

Solution 1

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/

Solution 2

Give the menu's table tag an id and then:

#menu-table td:hover { background: whatever; }

Really, though, you shouldn't be using tables for anything other than data tables, they are hard to maintain and break semantics.

Share:
14,797
Moon
Author by

Moon

Updated on June 04, 2022

Comments

  • Moon
    Moon almost 2 years

    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

  • Stephan Muller
    Stephan Muller over 13 years
    yeah, let's give all td's a class. Waste of bytes and especially of time when having to add/remove cells. In that case just give the table an ID and use table#id > td.
  • Stephan Muller
    Stephan Muller over 13 years
    ^ This. I could remove my answer, this one should win.
  • Delan Azabani
    Delan Azabani over 13 years
    Much better idea, thanks. Also, the > shouldn't be used because it implies direct descendency, which the td is not (it's in a tr).
  • Moon
    Moon over 13 years
    and it did.. @RoToRa : i am not good at CSS.. can you please help me with this as well jsfiddle.net/Dk9fD
  • Moon
    Moon over 13 years