Reputation: 1218
So I'm trying to show a gradient over an image when the user hovers over it. I'm doing this via :before and adding it that way.
My html layout is like so:
<div class='portfolio_thumb'>
<div class='portfolio_thumb_caption'></div
</div
and my CSS for those items
.portfolio_thumb {
width: 100%;
height: 300px;
background-size: cover;
}
.portfolio_thumb .portfolio_thumb_caption:before {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: linear-gradient(to bottom, rgba(72,76,97,0) 0%, rgba(72,76,97,0.8) 75%);
content: '';
opacity: 0;
transform: translate3d(0,50%,0);
}
.portfolio_thumb:hover .portfolio_thumb_caption:before {
transform: translate3d(0,0,0);
opacity: 1;
}
But my problem is that when I hover over the image, the gradient shows up but it covers my whole content area (not the footer or header), shouldn't the gradient only be over the that main div" The portfolio_thumb div? From the examples I've seen online that seems to be the case, but if it isn't how do they achieve that?
Thanks!
Upvotes: 0
Views: 591
Reputation: 30999
Add this to your CSS:
.portfolio_thumb {
position: relative;
}
A pseudo element is still a child of its parent, so if you want to absolutely position it relative to its parent (or one of the grand parents) (and use the (grand)parent's width and height in percentages as well in the pseudo element's definition), you need to explicitly define the positioning on its (grand)parent. What happens is that this establishes a context with the immediate (grand)parent that has the explicit positioning definition.
Upvotes: 1