Ralf Schneider
Ralf Schneider

Reputation: 3

Need both background image and link text color in a table cell to change on mouse hover over the cell (with CSS)

Sorry for a novice's question, but I am about to give up having spent whole day on this issue... I have searched this forum for a few hours, but still can't get the thing to work.

Would anyone assist me with CSS solution to the following problem please?

Basically, I have a table cell with an image background and a text link. I need the image and link color to change on mouse hover over this table cell at the same time. My cumbersome code looks about like this:

<table>
  <tr>
    <td width="160" height="36" align="center" valign="middle" class="menuitem1">
       <a href="http://www.samplesite.com">About us</a>
    </td>
  </tr>
</table>`

Then I tried all this in a CSS file:

.menuitem1 {
   border-right-width: 1px;
   border-right-style: solid;   
   border-right-color: #000;
   background-image: url("images/sample.png");
   background-repeat: no-repeat;
   background-position: left;
   padding-left: 17px;
}
.menuitem1 a:link{
   display: block;
   text-decoration: none;
   color: #fff;
}
.menuitem1 a:visited {
   text-decoration: none;
   color: #fff;
}
.menuitem1:hover {
   text-decoration: none;
   background-image: url("images/sample2.png");
   background-repeat: no-repeat;
   background-position: left;
   color: #000;
}
.menuitem1 a:hover {
   text-decoration: none;
   color: #000;
}
.menuitem1 a:active{
   color: #000;
}

The problem is that the text link doesn't follow block attribute. So the the text color changes only when mouse is over it, not over the rest of the cell. Adding width: 100% to .menuitem1 a still leaves 17px on the left (padding-left) that is not in the block. And it is even worse with the height: 100% has no effect and fixed height in px aligns the text vertically on top without possibility to change it.

Funny that if I don't have a hyperlink in the cell and have just text there, then this simple piece of code is sufficient for everything to work like a dream:

.menuitem1:hover {
   text-decoration: none;
   background-image: url("images/sample2.png");
   background-repeat: no-repeat;
   background-position: left;
   color: #000;
}

Isn't there a simple solution like that to the problem that occurs after adding a link?

Thank you very much in advance.

Upvotes: 0

Views: 1258

Answers (1)

Jeremy Blalock
Jeremy Blalock

Reputation: 2619

What many beginning javascript programmers don't at first realize, is that any list of selectors can be strung together to new selector. So to change the background image, you are right in putting:

.menuitem1:hover {
    background-image: url("images/sample2.png");
    background-repeat: no-repeat;
    background-position: left;

But to select the a element, you should use the following format:

.menuitem1:hover a {
    color: #000;
    text-decoration: none;
    ...
}

Hope this helps!

Upvotes: 1

Related Questions