CSS Scale animation also moves image to left?

匆匆过客 提交于 2021-02-16 15:55:29

问题


I'm trying to make an image gallery that uses CSS animations, but I'm having some weird effects come up. I have a smaller thumbnail image to start, and I want it to scale to twice the size when I hover over it. That part works, but it also makes it move to the left, and it ends up going over the edge of the screen. What should I do to fix it?

<style>
    .zoom {
        transition:1s ease-in-out;
    }
    .zoom:hover {
        transform:scale(2);
    }
</style>

<div class="content">
    <div class="zoom">
        <img alt="Paperplane" src="Paperplane.png" style="width: 200px; height: 62px">
        <br> <span class="caption">A paper plane</span>
    </div>
</div>

Demo


回答1:


It's not moving to the left. The left edge is moving, however, as is the right. Because your content is left-aligned, it appears to move left.

Demo

You could set the transform origin:

.zoom {
    transition: 1s ease-in-out;
    transform-origin: left top;
    background: pink;
}

Demo

Also consider simply using a less dramatic transform:

transform: scale(1.1);



回答2:


As isherwood described, the error is due to the fact that .zoom is taking up the full width, not just the visible part.

Another solution would be size .zoom so that it only takes up the amount of space that you want, in this case the width of the image. You can do this by giving it an explicit width.

.zoom {
    transition:1s ease-in-out;
    width:200px;
}

However, since the element still transforms from the middle, it will still go outside of the viewport since it's so close. To remedy this, you could use transform-origin:left or provide enough room on either side so that the scaled version does not go outside of the viewport. I used padding to do so in this demo.

One other note: it's not good to scale things past their default value, scale(1), because they become blurry from being too big. As a result, you could size your elements to width:400px; and give it transform:scale(.5) by default and go to transform:scale(1) on hover and it'd remove this issue.

Demo with all the changes

Also note that embedded styles are bad, you should use the external stylesheet nearly all of the time.




回答3:


or if you need immutable area of image, you can try add overflow:hidden container.

For this example use class content before zoom class:

.content{
    overflow:hidden;
}

http://jsfiddle.net/3b7afm7z/6/


and you can combine both, for this example entry:

.content{
    overflow:hidden;
}
.zoom:hover {
    transform:scale(2);
    transform-origin: left bottom;
}

http://jsfiddle.net/3b7afm7z/9



来源:https://stackoverflow.com/questions/26853409/css-scale-animation-also-moves-image-to-left

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!