Member Avatar for adrian.mcguinness

Hi,
I have several image tags overlapping using css and am able to use hover to make the one selected move to the top of he pile.

#gallery  img{
float: left;
width: 250px;
height: 250px;
position: relative;
}

#gallery img:nth-child(2) {
left: -200px;
}


#gallery img:hover{
z-index: 10;
}

I am unable to make the hovering item stay on top of the pile img:active does not work.
If i add anchor tags around the image tags the positioning does not work.

I am not sure what to do.

Recommended Answers

All 5 Replies

When do you want the active (hovered) image stay on top? I mean if you take of the cursor of the image, it will go back to it's original state and that's how hover works. The :active pseudo class can't help you with this either. You can't do this with CSS alone, you'll need JavaScript to trigger an event that keeps the image on top once you hovered it and go back once you hovered another image in the stack.
Actually, there might be a CSS only solution, but then you will have to use a CSS transition with an 'infinite' delay which is kind of a 'hacky' solution :).

Member Avatar for adrian.mcguinness

How can I use javascript to make the img active

With jQuery you can do something like this:

$(function() {
  $('img').mouseenter(function() {
    $(this).addClass('active').siblings().removeClass('active')
  });
});

The .active class has the higher z-index in your CSS.

Little demo: http://cssdeck.com/labs/full/jwprgxso

Member Avatar for adrian.mcguinness

Got it. I hadnt put a jquery script tag in. Thanks alot

Here's the full code of that demo. Apologies for the unreadability. I did indent the code, but for some reason it doesn't show up fully indented.

<!doctype html>
<html>

<head>

<style>

    .gallery {
      position: relative;
      margin: 200px;
    }

    .gallery img {
      position: absolute;
      z-index: 0;
    }

    .gallery img:nth-child(1) {
      left: -25px;
      transform: rotate(-7deg)
    }

    .gallery img:nth-child(3) {
      left: 25px;
      transform: rotate(7deg)  
    }

    .gallery img.active {
      z-index: 10;
    }

</style>

</head>

<body>

    <div class="gallery">
        <img src="http://placehold.it/200x250/3ebecc/000000&text=image+1">
        <img src="http://placehold.it/200x250/4eb7a3/000000&text=image+2">
        <img src="http://placehold.it/200x250/c6b654/000000&text=image+3">

    </div>

    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    <script>
        $(function() {
            $('img').mouseenter(function() {
                $(this).addClass('active').siblings().removeClass('active')
            });
        });
    </script>

</body>

</html>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.