Reputation: 75
I want to create the following hover effect: on hover, one div (.left
) is supposed to expand to full width and cover another div (.right
).
This is what I have so far (jsfiddle):
HTML
</div>
<div class="right">
<img src="https://res.cloudinary.com/ddofbxz8d/image/upload/v1548087392/ka6fgbjakjeskramtkew.jpg">
</div>
</div>
CSS
.container {
width: 100%;
}
.left {
width: 67%;
height: 100%;
background: blue;
float: left;
}
.right {
width: 33%;
height: 100%;
float: right;
z-index: -1;
}
img {
max-width: 100%;
height: auto;
margin: 0;
}
.container:hover .left {
width: 100%;
}
JS (JQuery)
$(".container").css({'height':($("img").height()+'px')});
Explanation/Requirements:
The image has an aspect ratio of 1:1. The height of the .container
div should be the height of the image, which in turn is supposed to have a width of 33% of the .container
div.
Problem
Why is the image being pushed down, although its z-index is set to -1?
I tried multiple different approaches that I found online, but they are not working in my case. For example, I don't want to set the position of the .right
div to position: absolute
since I this would ignore the padding of the .container
div.
How can I solve this problem?
Upvotes: 1
Views: 160
Reputation: 273710
Consdier a negative margin to avoid pushing the image to the next line. You can also simplify your code using flexbox instead of float and you will no more need the JS code to set the height:
.container {
width: 100%;
display:flex;
flex-wrap:wrap; /*it will work even wrap enabled*/
}
.left {
width: 67%;
background: rgba(0,0,255,0.8);
transition:1s;
}
.right {
width: 33%;
z-index:-1;
}
img {
max-width: 100%;
height: auto;
margin: 0;
display:block;
}
.container:hover .left {
margin-right:-33%;
width:100%;
}
<div class="container">
<div class="left">
</div>
<div class="right">
<img src="https://res.cloudinary.com/ddofbxz8d/image/upload/v1548087392/ka6fgbjakjeskramtkew.jpg">
</div>
</div>
Upvotes: 3