【问题标题】:CSS: How to scale an image from the center instead of top-leftCSS:如何从中心而不是左上角缩放图像
【发布时间】:2015-04-27 21:13:21
【问题描述】:

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

max-width: 100% 

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

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

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

【问题讨论】:

标签: css scale center transition


【解决方案1】:

只需在:hover 上将width: 400px; 替换为transform: scale(2,2)

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>

【讨论】:

【解决方案2】:

将此添加到div:hover

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

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

【讨论】:

  • 哦,我明白了。这很好。不完美,但可以通过适当的 % 值来完善。谢谢!这也给了我一个使用边距的想法,我在这里使用另一种方法更新了我的小提琴:jsfiddle.net/Eolis/3ya98xh8/5
  • 它应该是完美的,但我不知道为什么它会改变一点。
  • 这里有一个更好的方法:jsfiddle.net/3ya98xh8/6。在这里您不必使用任何硬编码值。
【解决方案3】:

别忘了设置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/

【讨论】:

    【解决方案4】:

    如果对任何人都有帮助,不妨提出我的解决方案:

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

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-22
    • 1970-01-01
    • 2017-11-30
    • 1970-01-01
    • 1970-01-01
    • 2015-09-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多