I'm trying to show a link that appears when I hover over the image. The goal is to fade the image and bring out the link with its background. I tried to do this but I'm doing something wrong. The background of the div comes out of the container. Also I don't know if the opacity method is the right one for hiding and showing.
Also I can't center the link in the image vertically or horizontally
Sorry, I'm new and just don't know how to fix. Someone show me the right way and tell me what I'm doing wrong?
I appreciate any response. Thank you.
.container_left {
width: 20%;
}
.boxItems_first {
display: flex;
flex-direction: column;
}
.boxItems_first a {
position: absolute;
opacity: 0;
}
.boxItems_first:hover a {
position: absolute;
background: black;
width: 100%;
bottom: 60%;
color: #fff;
opacity: 1;
transition: 0.3s;
}
.boxItems_first:hover img {
opacity: 0.3;
transition: 0.3s;
}
<div >
<div >
<a href="https://mywebsite.com/shop/product" target="_blank">Product Page</a>
<img width="auto" height="200" src="https://c.wallhere.com/photos/e5/d3/vertical_animation_fantasy_art-1693403.jpg!d" alt="" loading="lazy">
</div>
</div>
CodePudding user response:
You're not too far off. The main thing you're missing is position:relative
on the container, otherwise your position:absolute
elements will be positioned based on the entire viewport.
You will also want to make sure your transition
rules are not just applied on hover - the fade in/out looks quite janky otherwise. As a general rule, put your styles in the base class and only apply changes on hover.
Definitely more than one way to solve this problem but the approach of using position:absolute
on the link element and transitioning the opacity on hover is fine. You just need to make the link 100% height and width and then use flex to align its children. Put a <span>
around the link text so you can style that for the black background if you want it.
I've made some assumptions based on your post but this snippet should get you started:
.container_left {
width: 20%;
}
.boxItems_first {
display: flex;
position: relative;
flex-direction: column;
}
.boxItems_first img {
transition: all 0.3s linear;
}
.boxItems_first a {
position: absolute;
opacity: 0;
z-index: 1;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
transition: all 0.3s linear;
color: white;
}
.boxItems_first a span {
background: black;
text-align: center;
padding: 3px;
display: inline-block;
}
.boxItems_first:hover a {
opacity: 1;
}
.boxItems_first:hover img {
opacity: 0.3;
}
<div >
<div >
<a href="https://mywebsite.com/shop/product" target="_blank"><span>Product Page</span></a>
<img width="auto" height="200" src="https://placedog.net/600" alt="" loading="lazy">
</div>
</div>