CSS:如何从中心而不是左上角缩放图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28726430/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 03:02:00  来源:igfitidea点击:

CSS: How to scale an image from the center instead of top-left

cssscalecentertransition

提问by Eolis

So my problem is that I have an image and I set its CSS to have a

所以我的问题是我有一个图像,我将它的 CSS 设置为

max-width: 100% 

which scales it at lower resolutions ( as will be seen in the fiddle below ). What I want is for the transition to take effect from the center of the image.

以较低的分辨率对其进行缩放(如下面的小提琴所示)。我想要的是过渡从图像的中心生效。

Currently; and from what I have seen from most the transitions I have done involving scale they expand from the top-left corner.

目前; 从我从我所做的涉及比例的大多数过渡中看到的情况来看,它们从左上角扩展。

here is my fiddle: http://jsfiddle.net/Eolis/3ya98xh8/3/

这是我的小提琴:http: //jsfiddle.net/Eolis/3ya98xh8/3/

回答by Gildas.Tambo

Just replace width: 400px;with transform: scale(2,2)on :hover.

只需替换width: 400px;transform: scale(2,2)on :hover

img {
    width: 100%; max-width: 100%;
}
div {
    position: absolute; left: 20%; top: 20%;
    width: 250px;
    transition: all 2s ease-in-out;
}
div:hover {
    transform: scale(2,2)
}
<div>
    <a href="http://photobucket.com/images/cat" target="_blank">
        <img src="http://i583.photobucket.com/albums/ss278/campipr/coolcat.gif" border="0" alt="cat photo: cat coolcat.gif"/>
    </a>
</div>

回答by Anupam Basak

Add this to the div:hover:

将此添加到div:hover

transform: translateX(-25%) translateY(-25%);

Here is the Fiddle: http://jsfiddle.net/3ya98xh8/4/

这是小提琴:http: //jsfiddle.net/3ya98xh8/4/

回答by Eolis

may as well throw my solution up in case it is helpful to anyone:

不妨抛出我的解决方案,以防它对任何人有帮助:

::CSS::

:: CSS::

img {
    width: 100%; max-width: 100%;
}
div {
    position: absolute; left: 50%; top: 50%;
    margin-left: -125px; margin-top: -100px;
    width: 250px;
    transition: all 2s ease-in-out;
}
div:hover {
    margin-left: -200px; margin-top: -150px;
    width: 400px;
}

::HTML::

::HTML::

<div>
    <a href="http://photobucket.com/images/cat" target="_blank">
        <img src="http://i583.photobucket.com/albums/ss278/campipr/coolcat.gif" border="0" alt="cat photo: cat coolcat.gif"/>
    </a>
</div>

::Fiddle::http://jsfiddle.net/Eolis/3ya98xh8/5/

::小提琴:: http://jsfiddle.net/Eolis/3ya98xh8/5/