背景图片和背景颜色之间的CSS过渡

时间:2017-07-31 12:28:19

标签: css css-transitions

我正在尝试在带有背景图像的面板上进行基本的缓出转换。我希望它在悬停时淡化为背景色。我尝试过使用各种非正常工作的转换。我已经尝试过(我认为可行):

transition:background-image 0.2s ease-in-out;

.panel {
  width:200px;
  height:200px;
  background:#000 url("https://cdn.pixabay.com/photo/2016/03/28/12/35/cat-1285634_1280.png") no-repeat center center / cover;
  transition:background-image 0.2s ease-in-out;
}
.panel:hover {
  background:#000;
  transition:background-image 0.2s ease-in-out;
}
<div class="panel"></div>

4 个答案:

答案 0 :(得分:1)

您可以使用此代码:

演示在这里:https://output.jsbin.com/yadiwoviwe

.panel {
  position: relative;
  background: rgba(0,0,0,0) url(https://cdn.pixabay.com/photo/2016/03/28/12/35/cat-1285634_1280.png) no-repeat center center / cover;
  width:200px;
  height:200px;
  transition: background-color 0.2s ease-in-out;
}
.panel:hover {
  background-color: rgba(0,0,0,.5);
}
.panel:before {
  position: absolute;
  top: 0; right: 0; bottom: 0; left: 0;
  background-color: inherit;
  content: ' ';
}

答案 1 :(得分:1)

不幸的是,你不能以这种方式这样做

原因是您正在尝试为background-image属性设置动画 - 这是一个不可动画的属性。

相反,您可以使用一个很酷的小技巧,使用伪元素来创建背景图像:

&#13;
&#13;
.panel {
  width: 200px;
  height: 200px;
  position: relative;
  background: pink;
}

.panel::after {
  content: "";
  position: absolute;
  pointer-events: none;
  background: url(https://unsplash.it/200) center center no-repeat;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 1;
  will-change: opacity;
  transition: opacity .1s ease-out;
}

.panel:hover::after {
  opacity: 0.5;
}
&#13;
<div class="panel"></div>
&#13;
&#13;
&#13;

受CSSTricks的this cool little article启发

答案 2 :(得分:0)

背景图像不可动画,您无法在backgronund-image属性上添加转场。 您可以使用其他解决方法解决此问题,如@CGK答案

background: rgba(0,0,0,0) url(https://cdn.pixabay.com/photo/2016/03/28/12/35/cat-1285634_1280.png) no-repeat center center / cover;

答案 3 :(得分:0)

或者,您可以操纵图像的不透明度。

&#13;
&#13;
.panel {
  width: 200px;
  height: 200px;
  background: #000;
  position: relative;
  color: white;
  text-align: center;
}

.panel:after {
  content: "";
  background-image: url('https://cdn.pixabay.com/photo/2016/03/28/12/35/cat-1285634_1280.png');
  background-size: 200px 200px;
  position: absolute;
  top: 0;
  left: 0;
  width: 200px;
  height: 200px;
  opacity: 1;
  transition: opacity 0.2s ease-in-out;
}

.panel:hover:after {
  opacity: 0;
}
&#13;
<div class="panel"><h1>Text</h1></div>
&#13;
&#13;
&#13;