简体   繁体   English

如何在 css 中平滑悬停时为背景图像大小设置动画?

[英]How do I animate background image size on hover smoothly in css?

I have a div with a background image.我有一个带有背景图像的 div。 On hover, I want the image to zoom in slightly.在悬停时,我希望图像稍微放大。 I have it working (see fiddle) but I want it to animate smoothly over 0.3 seconds and then go back smoothly instead of jumping.我让它工作(见小提琴),但我希望它在 0.3 秒内平滑地动画,然后平滑地返回而不是跳跃。

How do I do this?我该怎么做呢?

https://jsfiddle.net/ufgnroor/2/ https://jsfiddle.net/ufgnroor/2/

HTML HTML

                <div class="portfolio-item">

                </div>

CSS CSS

.portfolio-item {
height: 300px;
position: relative;
text-align: center;
cursor: pointer;
margin-bottom: 20px;
background-position: center;
background-size: cover;
background-image: url('http://media4.popsugar-assets.com/files/2014/08/08/878/n/1922507/caef16ec354ca23b_thumb_temp_cover_file32304521407524949.xxxlarge/i/Funny-Cat-GIFs.jpg');
}

.portfolio-item:hover {
background-size: 150%;
-webkit-transition: all 0.3s ease-in-out;
}

Use Transform scale.使用变换比例。 You will need a wrapper too so the image dosent overflow你也需要一个包装器,这样图像就会溢出

<div class="wrapper">
    <div class="portfolio-item">
    </div>
</div>

.portfolio-item:hover {
    -webkit-transform: scale(1.5,1.5);
    -webkit-transition: all 0.3s ease-in-out;
}

Demo演示

For your case you have to set the background-size & the transition before the hover:对于您的情况,您必须在悬停之前设置背景大小和过渡:

.portfolio-item {
    background-size: 100%;
    -webkit-transition: all 0.3s ease-in-out;
}

.portfolio-item:hover {
    background-size: 150%;
}

https://jsfiddle.net/gv5pjqok/1/ https://jsfiddle.net/gv5pjqok/1/

Instead of using background-size: 150% use transform.而不是使用背景大小:150% 使用变换。 Here's an example:下面是一个例子:

.portfolio-item:hover { transform: scale(1.5); transition: all 2s ease-in; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM