user2066880
user2066880

Reputation: 5034

Non-opaque text in opaque background

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;
}

Upvotes: 0

Views: 82

Answers (1)

SW4
SW4

Reputation: 71160

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);
}

Upvotes: 5

Related Questions