Reputation: 107
I've noticed an unanticipated effect of using CSS color transitions on an image with a transparent background. Here's an example:
:root {
--size: 4em;
--duration: 5s;
}
html, body {
margin: 0;
background: slategray;
color: white;
}
.main-menu {
overflow: hidden;
background: black;
}
.main-menu *:hover {
background: skyblue;
-webkit-transition-duration: 5s;
transition-duration: var(--duration);
}
.image-div {
float: right;
padding: calc(var(--size) / 2);
-webkit-transition-duration: 5s;
transition-duration: var(--duration);
}
.image {
max-width: var(--size);
}
<div class="main-menu">
<div class="image-div">
<img class="image" src="https://s4.postimg.org/5zy6kjqcd/maximize.png"/>
</div>
</div>
To summarize, the issue is this. If you hover over the image-div div's padding, the background color of this div and the contained image div execute the color transition at the same rate, as expected. However, if you hover over the image div, its color appears to transition slightly faster than the image-div div's color.
Given the fact that I was able to reproduce this exact behavior on Firefox, Chrome, Safari and Edge, I get the feeling that this is expected behavior, but I would like to understand why it is happening.
Upvotes: 2
Views: 260
Reputation: 87231
Given the fact that I was able to reproduce this exact behavior on Firefox, Chrome, Safari and Edge, I get the feeling that this is expected behavior, but I would like to understand why it is happening.
The reason this happens is because the img
transition picks up the image-div
transitioned color, hence get lighter faster.
Simply put, the image-div
goes from a solid black, while the img
goes from black that turns into sky blue.
Additionally, since you move the mouse over the image-div
before it gets to the img
, the transition starts before, though the delay is based on how fast you move the mouse to the img
Upvotes: 1
Reputation: 42352
When you hover over the img
two hover events are triggered - one on the img
and one on its parent image-div
when you use *
in .main-menu *:hover
selector:
Instead use the hover only on the image-div
as below:
.main-menu .image-div:hover {
background: skyblue;
}
and now the difference in transition
will not be there - see demo below:
html, body {
margin: 0;
background: slategray;
color: white;
}
.main-menu {
overflow: hidden;
background: black;
}
.main-menu .image-div:hover {
background: skyblue;
}
.image-div {
float: right;
padding: calc(4em / 2);
-webkit-transition-duration: 5s;
transition-duration: 5s;
}
.image {
max-width: 4em;
}
<div class="main-menu">
<div class="image-div">
<img class="image" src="https://s4.postimg.org/5zy6kjqcd/maximize.png"/>
</div>
</div>
Upvotes: 2