I have an image that is absolutely positioned using vh
units. I want to animate this positioning use CSS. When doing so, however, the relative nature of vh
units seems to be lost. To illustrate, look at the following two examples. In both of them, drag the bottom of your browser up and down to change its height.
The positioning adjusts correctly in relation to the screen height.
http://codepen.io/maxedison/pen/jPOQPW
#mountain { position: absolute; left: 50%; top: 55vh; opacity: 1; } img { width: 180vh; margin-left: -50%; }
<div id="screen1"> <div id="mountain"> <img src="http://upload.wikimedia.org/wikipedia/commons/2/20/Red_Slate_Mountain_1.jpg"> </div> </div>
Animation
The positioning does NOT adjust at all. It's like the vh
unites have turned into static px
, maintaining the same distance from the top of the window regardless of screen height.
http://codepen.io/maxedison/pen/QbWJbj
#mountain { position: absolute; left: 50%; top: 100vh; opacity: 0; -webkit-animation: lincoln_page_load 2s ease forwards; animation: lincoln_page_load 2s ease forwards; } img { width: 180vh; margin-left: -50%; } @-webkit-keyframes lincoln_page_load { to { opacity: 1; top: 55vh } } @keyframes lincoln_page_load { to { opacity: 1; top: 55vh } }
<div id="screen1"> <div id="mountain"> <img src="http://upload.wikimedia.org/wikipedia/commons/2/20/Red_Slate_Mountain_1.jpg"> </div> </div>
Any ideas on how to correct this? I know I can resort to JavaScript to make this work :)
This is only a problem when the animation is paused with forwards
and the animation is still active:
Place the top: 55vh
in #mountain
so that when the animation ends it has this value and remove the opacity: 0
Remove forwards
so that the animation is completed
Add the opacity: 0
and top: 100vh
to from
in the keyframes so that these values are present when the page loads
This has the added benefit of showing the image if the browser does not support the animation
property.
Codepen Example with SASS (Auto-prefixer is turned on)
Here is another example using a transform — translate
( info link ) — which seems to provide a slightly smoother animation.
#mountain { position: absolute; left: 50%; top: 55vh; -webkit-animation: lincoln_page_load 2s ease; animation: lincoln_page_load 2s ease; } img { width: 180vh; margin-left: -50%; } @-webkit-keyframes lincoln_page_load { from { top: 100vh; opacity: 0; } to { opacity: 1; top: 55vh } } @keyframes lincoln_page_load { from { top: 100vh; opacity: 0; } to { opacity: 1; top: 55vh } }
<div id="screen1"> <div id="mountain"> <img src="http://upload.wikimedia.org/wikipedia/commons/2/20/Red_Slate_Mountain_1.jpg"> </div> </div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.