user1355300
user1355300

Reputation: 4987

CSS: Change position of div on hover

In the Following HTML, the initial position of .layer is set at top: -100%, I want to change it on hover over the .image div. I am trying following code but it does not seem do anything on hover.

HTML:

<div class="box">
    <div class="image">
        <a href="#"><img src="http://farm9.staticflickr.com/8356/8332233161_18e3a75de0_m.jpg" ></a>
    </div>
    <div class="layer">Hide it first, show on hover over image</div>
     <div class="other">other</div>
</div>

CSS:

.box{
    border: 1px solid red;
    width: 240px;
}

.box .image{
    position: relative;
    overflow: hidden;    
}

.box .layer{
    width: 240px;
    height: 146px;
    background: green;
    position: absolute;
    top: -100%;
}

.box .image:hover .layer{
    top: 0  
}

JSFiddle: http://jsfiddle.net/pY9jx/

Upvotes: 0

Views: 5006

Answers (2)

David Thomas
David Thomas

Reputation: 253318

The problem was the selector you were using, a space between elements implies the second element is a descendant of the former, whereas in this case the elements are adjacent siblings, a relationship described using the + combinator; therefore:

.image:hover + .layer,
.layer:hover {
    top: 0  
}

JS Fiddle demo.

The reason that I've also defined the rule to apply to the .layer:hover is to avoid the flickering that otherwise results when the .layer is placed under the cursor, which stops the .layer:hover selector applying (as the .layer is, effectively, 'in the way').

References:

Upvotes: 6

Boaz
Boaz

Reputation: 20230

The style rule of the hover state applies to .box .image:hover .layer. This means it would be applied to an element of class layer that is nested within an element of class image. However, in your current code the layer element is not nested inside the image element.

To solve this, simply move the layer element into the image element, like so:

<div class="box">
<div class="image">
    <a href="#"><img src="http://farm9.staticflickr.com/8356/8332233161_18e3a75de0_m.jpg" ></a>
    <div class="layer">Hide it first, show on hover over image</div>
</div>
<div class="other">other</div>

Test it in action here: http://jsfiddle.net/pY9jx/3/

Upvotes: 1

Related Questions