Reputation: 476
So I have an envelope image and a letter image and I want the letter to smoothly transition out of the envelope onmouseover
and I want the letter to smoothly transition back to place onmouseout
. Now the first mouseover is perfect, the envelope slides to a -400px
width in order to reveal the letter at a 1 second transition, but onmouseout
, the envelope harshly snaps back to place and I have no idea why. Also, any additional mouseovers after the mouseout, it harshly snaps both the onmouseover
and onmouseout
events. Here is the code:
<!doctype html>
<html lang='en-us'>
<head>
<title>Test animation</title>
<style>
.displayNow {
display: flex;
flex-direction: row;
justify-content: flex-end;
position: relative;
}
.letter {
position: absolute;
}
.envelope {
position: absolute;
transition: width 1s ease-in-out;
transition-timing-function: linear;
-webkit-transition: 1s ease-in-out;
-webkit-transition-timing-function: linear;
}
</style>
<script>
function moveOut() {
var cssString = "margin-left:-400px;";
document.getElementById('envelope').style.cssText=cssString;
}
function moveIn() {
var cssString = "margin-left:auto;";
document.getElementById('envelope').style.cssText=cssString;
}
</script>
</head>
<body>
<div class='displayNow'>
<!-- Letter -->
<img src='Letter.png' class='letter' id='letter' onmouseover='moveOut()' onmouseout='moveIn()' alt='letter'>
<!-- Envelope -->
<img src='Envelope.png' class='envelope' id='envelope' onmouseover='moveOut()' onmouseout='moveIn()' alt='envelope'>
</div>
</body>
</html>
I have also tried a :hover
selector as opposed to the onmouseout/in JavaScript event which produced the same result.
Upvotes: 3
Views: 4023
Reputation: 476
For anyone who is coming to this question with similar issues (not seeing transitions work with auto dimensions) here is a great article from css-tricks on why it happens and what you can do to prevent it
Using CSS Transitions on Auto Dimensions
Upvotes: 0
Reputation: 503
Instead of setting margin-left to auto, set it to 0 (or wherever else it's supposed to originally sit at)
I believe CSS3 transitions do not know how to handle the auto settings. This will apply to any transitionable element that can be set to auto. I have ran into this problem several times when trying to transition heights and widths.
As far as the issue of snapping both ways after the initial transition, I'm not sure if that is related to the margin-left:auto
issue or not but I would be willing to bet that it will fix it
Upvotes: 3