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

25

需要翻译的内容已经在第一个段落中结束了,没有后续内容需要翻译。
max-width: 100% 

如下所示的小玩意儿将在较低的分辨率下进行缩放,我希望过渡效果从图像中心开始生效。

目前大多数涉及缩放的转换都是从左上角扩展的。

这是我的小玩意儿:http://jsfiddle.net/Eolis/3ya98xh8/3/


4个回答

35

通过在 :hover 上使用 transform: scale(2,2) 替换 width: 400px;

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>


transform-origin: center; ? - oCcSking
2
@oCcSking,它是默认值Default value: 50% 50% 0,如规范所述 https://developer.mozilla.org/en-US/docs/Web/CSS/transform-origin Initial value 50% 50% 0 - Gildas.Tambo

9

哦,我明白了。这很不错。虽然不完美,但可以通过适当的%值来完善它。谢谢!这也给了我一个使用边距的想法,我已经使用另一种方法更新了我的fiddle,链接在这里:http://jsfiddle.net/Eolis/3ya98xh8/5/ - Eolis
1
它本应该是完美的,但我不知道为什么它有些偏移。 - Anupam Basak
3
这是更好的方法:http://jsfiddle.net/3ya98xh8/6/。在这里,您不需要使用任何硬编码值。 - Anupam Basak

6

不要忘记设置 transform-origin 属性

.current{
    top: 0px;
    left: 0px;
    z-index: 2;
    opacity: 1;
    transform: scale(0.9, 0.9);
    transition: opacity 1.6s ease-out 0s, transform 7.2s linear 0s;
    transform-origin: center center;
    animation: normal;
}

https://css-tricks.com/almanac/properties/t/transform-origin/


1

为了帮助其他人,我也可以分享一下我的解决方案:

::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::

<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/


2
这里有一个更好的方法:http://jsfiddle.net/3ya98xh8/6。在这里,您不必使用任何硬编码值。 - Anupam Basak

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接