0

I am trying to show the child picture when hovering over the parent picture. Currently, when setting up a CSS hover styling on the parent picture, the child picture never becomes visible.

However, if I change the css hover styling to reference the .picture-container element instead of the .parent-picture, it works as intended. Why is this?

This doesn't seem to be related to the parent image element being an absolute element.

https://jsfiddle.net/9gnoLu81/1/

.picture-container {
    width:300px;
    height:300px;
    float:left;
    position:relative;
}

.parent-picture {
    float:left;
    width:100%;
    height:100%;
    position:absolute;
    top:0;
    left:0;
}

.child-picture {
    position:absolute;
    top:0;
    right:0;
    border:1px solid red;
    width:100px;
    height:100px;
    display:none;
}

.parent-picture:hover .child-picture {
    display:block;
}
<div class="picture-container">
        <img src="https://picsum.photos/200" alt="" class="parent-picture">    
        <img src="https://picsum.photos/200" alt="" class="child-picture">
</div>



    
Marik Ishtar
  • 2,406
  • 1
  • 9
  • 22
AnchovyLegend
  • 10,873
  • 31
  • 123
  • 211

1 Answers1

4

This is because you are using .parent-picture:hover .child-picture which means child-picture is inside the parent-picture which is not true, but child-picture is inside the picture-container, you need to use sibling selectors,

adjacent sibling selector (+)

general sibling selector (~)

.picture-container {
    width:300px;
    height:300px;
    float:left;
    position:relative;
}

.parent-picture {
    float:left;
    width:100%;
    height:100%;
    position:absolute;
    top:0;
    left:0;
}

.child-picture {
    position:absolute;
    top:0;
    right:0;
    border:1px solid red;
    width:100px;
    height:100px;
    display:none;
}

.parent-picture:hover + .child-picture {
    display:block;
}
<div class="picture-container">
        <img src="https://picsum.photos/200" alt="" class="parent-picture">    
        <img src="https://picsum.photos/200" alt="" class="child-picture">
</div>
Marik Ishtar
  • 2,406
  • 1
  • 9
  • 22