Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS hover on div doesn't affect anchor that sits inside?

Tags:

html

css

<style>
      .btn{
           display: inline-block;
           padding: 15px 10px;
           background: gray;
       }
      .btn:hover{
             background:lightgray;
             color:red;
      }
</style>

<div class="btn"> 
   text
</div>

works nicely. However if we have that:

<div class="btn"> 
  <a href="#">text</a>
</div>

it wouldn't work exactly as the first one. The anchor's text wouldn't be affected. Okay what if we add to the CSS:

.btn a:hover{
    background:lightgray;
   color:red;
 }

That will work, but only if you hover exactly on the anchor, but still hover on the div rectangle wouldn't affect the anchor's text.

How can I tweak that without any javascript, so both rectangles acted identically?

http://jsfiddle.net/vaNJD/

UPD: adding !important keyword wouldn't help

like image 624
iLemming Avatar asked Aug 10 '11 16:08

iLemming


2 Answers

Because all web browsers set a default color (and text-decoration) for a elements, you need a more specific selector to override the default. Try this instead:

.btn:hover, .btn:hover a {
    background:lightgray;
    color:red;
}

If you really want the two boxes to be identical, you would also need to override the un-hovered button as well:

.btn a {
    color: black;
    text-decoration: none;
}

It may also be worth pointing out that IE6 only supports the :hover pseudo-class on a elements. You may want to work around this by setting the a to display: block and adding the background color there.

You can accomplish the same effect by getting rid of the container and applying the .btn class directly to the a element. See the third box in this updated fiddle: http://jsfiddle.net/mlms13/vaNJD/5/

like image 75
Michael Martin-Smucker Avatar answered Nov 15 '22 00:11

Michael Martin-Smucker


     .btn:hover{
             background:lightgray;
             color:red;
      }
      .btn:hover a{
        color: red;
      }
like image 41
Tim Hoolihan Avatar answered Nov 14 '22 22:11

Tim Hoolihan