I have an image, and I want that when I hover over the image a black background with little opacity cover the image and a button on top of the image appear. Write now I put the button in the place where I want to but I can't make it disappear and appear when I hover.
<div class="container">
<img src="img_snow.jpg" alt="Snow">
<button class="btn">Button</button>
</div>
.container {
position: relative;
button {
position: absolute;
top: 60%;
left: 50%;
transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
}
button:hover {
background-color: black;
}
}
img {
background-image: url(${({ src }) => src});
background-repeat: no-repeat;
background-size: cover;
&:hover {
background-color: #000;
opacity: 0.5;
}
}
I have used a pseudo element on the .container element with a background color with opacity. Rather than hovering over the image, I have shown the button when hovering over the container.
.container {
position: relative;
width:100%;
max-width:100px;
}
.container:before {
content:"";
position:absolute;
width:100%;
height:100%;
top:0;left:0;right:0;
background-color:rgba(0,0,0,0);
}
.container:hover::before {
background-color:rgba(0,0,0,0.5);
}
.container img {
display:block;
}
.container button {
position: absolute;
top: 60%;
left: 50%;
transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
opacity:0;
}
.container:hover button {
opacity: 1;
}
<div class="container">
<img src="http://placeimg.com/100/100/animals" alt="Snow">
<button class="btn">Button</button>
</div>
Use a pseudo element on the container and start it at 0 opacity. Same with the button. Then on hover of the container you change the opacity on those elements to make them appear. Transition property makes for a nice finishing touch on the interaction.
.container:before {
opacity: 0;
background: rgba(0, 0, 0, 0.5);
}
.container:hover:before {
opacity: 1;
}
And the button same thing:
.btn {
opacity: 0;
}
.container:hover .btn {
opacity: 1;
}
.container {
position: relative;
width: 400px;
height: 220px;
border: 2px solid black;
display: flex;
align-items: center;
justify-content: center;
}
.container:before {
/* empty pseudo */
content: '';
/* start transparent, include a transition bcuz */
opacity: 0;
transition: opacity 0.5s ease;
/* covers the whole div */
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.5);
z-index: 2;
}
.container:hover:before {
opacity: 1;
}
.container img {
position: absolute;
display: block;
max-width: 100%;
height: auto;
z-index: 1;
}
.btn {
opacity: 0;
transition: opacity 0.5s ease;
position: relative;
padding: 0 40px;
height: 40px;
line-height: 40px;
max-width: 260px;
cursor: pointer;
z-index: 3;
}
.container:hover .btn {
opacity: 1;
}
<div class="container">
<img src="https://picsum.photos/400/220" alt="Snow">
<button type="button" class="btn">Click Me</button>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With