css transition opacity fade background
287,870
Solution 1
Wrap your image with a span
element with a black background.
.img-wrapper {
display: inline-block;
background: #000;
}
.item-fade {
vertical-align: top;
transition: opacity 0.3s;
-webkit-transition: opacity 0.3s;
opacity: 1;
}
.item-fade:hover {
opacity: 0.2;
}
<span class="img-wrapper">
<img class="item-fade" src="https://via.placeholder.com/100x100/cf5" />
</span>
Solution 2
.container {
display: inline-block;
padding: 5px; /*included padding to see background when img apacity is 100%*/
background-color: black;
opacity: 1;
}
.container:hover {
background-color: red;
}
img {
opacity: 1;
}
img:hover {
opacity: 0.7;
}
.transition {
transition: all .25s ease-in-out;
-moz-transition: all .25s ease-in-out;
-webkit-transition: all .25s ease-in-out;
}
Solution 3
It's not fading to "black transparent" or "white transparent". It's just showing whatever color is "behind" the image, which is not the image's background color - that color is completely hidden by the image.
If you want to fade to black(ish), you'll need a black container around the image. Something like:
.ctr {
margin: 0;
padding: 0;
background-color: black;
display: inline-block;
}
and
<div class="ctr"><img ... /></div>
Related videos on Youtube
Author by
simon
Updated on July 09, 2022Comments
-
simon almost 2 years
I am doing a
transition
where it fades into transparent white, when a user is hovering an image.My problem is that I need to change the color, that it fades to, to black. I have tried just simply adding
background:black;
to the class that contains thetransition
, but it does not work unfurtunately, it's still fading into white transparent.The css code I am using is:
.hover:hover { opacity: 0.2; } .item-fade { background: black; opacity: 0.8; transition: opacity .25s ease-in-out; -moz-transition: opacity .25s ease-in-out; -webkit-transition: opacity .25s ease-in-out; }
<p>Hover image, the white opacity needs to be black :/</p> <img src="//placehold.it/100x100" class="hover item-fade" />
-
Zach Saucier over 10 yearsYour reasoning is wrong. It is because the image is currently being faded because it's overriding the background color