0

Spin on the popular question. In this case, I have a div that I want to darken when I mouseover, while not darkening the text inside it. I am halfway there; I can achieve this if I mouseover in the div anywhere besides the div that contains the text.

Here is my attempt: http://jsfiddle.net/59M7N/. Notice that if the mouse is over the top region of the box, the hover effect will not occur.

HTML

<div id="text">Hello World</div>
<div id="box">
    <div id="opaque"></div>
</div>

CSS

#box {
    height:200px;
    width:200px;
    border:5px solid black;
}

#opaque {
    position:absolute;
    width:200px;
    height:200px;
    background-color:black;
    opacity:0;
    -webkit-transition: opacity 0.3s ease-in-out;
    -moz-transition: opacity 0.3s ease-in-out;
    -ms-transition: opacity 0.3s ease-in-out;
    -o-transition: opacity 0.3s ease-in-out;
    transition: opacity 0.3s ease-in-out;
}

#opaque:hover {
    opacity:0.6;
}

#text {
    position:relative;
    color:blue;
    top:25px;
    left:10px;
    z-index:5;
}
user2066880
  • 4,825
  • 9
  • 38
  • 64
  • possible duplicate of [Transparent background, but not the content (text & images) inside it, in CSS only?](http://stackoverflow.com/questions/806000/transparent-background-but-not-the-content-text-images-inside-it-in-css-on) – Paulie_D Aug 04 '14 at 15:02
  • SW4's answer is the best solution, but if for whatever reason you want to retain your structure then you can use a complex selector like `#text:hover ~ #box > #opaque` and then change the opacity. (Strictly not recommended). – Harry Aug 04 '14 at 15:02
  • use `#text:hover ~ #box > #opaque{opacity:0.6;}` it works – Dev Man Aug 04 '14 at 15:03
  • http://jsfiddle.net/Paulie_D/59M7N/2/ – Paulie_D Aug 04 '14 at 15:03

1 Answers1

5

You can simplify both your HTML and CSS by adding a transition on a background RGBA color on the :hover, the last value being the opacity. As you are transitioning the background only, the text is unaffected.

Demo Fiddle

<div id="box">Hello World</div>

CSS

#box {
    height:200px;
    width:200px;
    border:5px solid black;
    color:blue;
    background:rgba(0, 0, 0, 0);
    transition:background 200ms ease-in;
}
#box:hover {
    background:rgba(0, 0, 0, .5);
}
SW4
  • 69,876
  • 20
  • 132
  • 137