CSS 背景图片大小转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23386784/
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 02:21:59  来源:igfitidea点击:

CSS Background image size transition

cssbackgroundhovertransition

提问by Chris Holstein

I am working on a simple markup with resizing a div's background img. See the fiddle:

我正在处理一个简单的标记,可以调整 div 的背景 img 的大小。见小提琴:

http://jsfiddle.net/zeYZL/

http://jsfiddle.net/zeYZL/

I need this to be animated with a simple CSS transition. and I tried doing this:

我需要使用简单的 CSS 过渡来制作动画。我尝试这样做:

#tile:hover {
    background-size:550px 550px;
    background-position:-50px -50px;
    transition:all 0.5s ease;
    -webkit-transition:all 0.5s ease;
    -o-transition:all 0.5s ease;
    -moz-transition:all 0.5s ease;

}

But then the background image clips upon the hover. (See http://jsfiddle.net/5Hm9u/)

但随后背景图像在悬停时剪辑。(见http://jsfiddle.net/5Hm9u/

Any tips on how to fix it?

有关如何修复它的任何提示?

Greetings, Chris

问候,克里斯

回答by Albzi

JSFiddle

JSFiddle

You need to put backgroundproperties outside the hovertoo, so it knows what to return to when not on hover.

您也需要将background属性放在外面hover,这样它就知道在不悬停时返回什么。

e.g.

例如

.tile{
  float:left;
  margin:1px;
  width:450px;
  height:450px;
  overflow:hidden;
  background-size:450px 450px;
  background-position:0px 0px;
}

And if you want it to transition on mouseover and when you take the mouse off, you put the transition on .tileand not .tile:hover

如果你想让它在鼠标悬停时过渡,当你取下鼠标时,你把过渡放在.tile而不是.tile:hover

JSFiddle

JSFiddle

Side note

边注

You should avoid using inline styles where you can use a stylesheet. Put your background image in .tilerather than using the styleattribute.

您应该避免在可以使用样式表的地方使用内联样式。放入您的背景图片.tile而不是使用该style属性。

Full CSS:

完整的CSS:

.tile{
  float:left;
  margin:1px;
  width:450px;
  height:450px;
  overflow:hidden;
  background-size:450px 450px;
  background-image:url(http://www.placehold.it/450x450);
  background-position:0px 0px;
  transition:all 0.5s ;
  -webkit-transition:all 0.5s ;
  -o-transition:all 0.5s ;
  -moz-transition:all 0.5s ;
}

.tile:hover {
  background-size:550px 550px;
  background-position:-50px -50px;
}

回答by Paulie_D

You have inline CSS which should be extracted to the initial CSS state.

你有内联 CSS,它应该被提取到初始 CSS 状态。

JSfiddle

JSfiddle

.tile{
    float:left;
    margin:1px;
    width:450px;
    height:450px;
    overflow:hidden;
    background-image:url(http://www.placehold.it/450x450);
    -webkit-background-size: 450px;
    background-size: ;
    background-position: center;
    transition:all 0.5s ease;

}
.tile:hover {
    background-size:550px 550px;

}