使用rgba颜色覆盖背景图像,具有CSS3过渡

15 css overlay background-image css3 css-transitions

今天早些时候,我问过Overlay背景图像,背景色为rgba.我的目标是使用背景图像的div,当有人悬停div时,背景图像会覆盖rgba颜色.在答案中,:after给出了一个解决方案:

#the-div {
    background-image: url('some-url');
}

#the-div:hover:after {
    content: ' ';
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    background-color: rgba(0,0,0,.5);
}
Run Code Online (Sandbox Code Playgroud)

我现在想要有相同的,但有一个CSS过渡:我想要淡入的背景颜色.我尝试添加transition: all 1s;#the-divCSS,但这不起作用.我也试着将它添加到#the-div:hover#the-div:after,但也不能工作.

有没有一种纯粹的CSS方法来为带有背景图像的div添加淡入淡出效果?

Ana*_*Ana 29

对的,这是可能的.

演示

.boo {
  position: relative;
  width: 20em; min-height: 10em;
  background: rgba(0,0,0,0) url(http://placekitten.com/320/160);
  transition: background-color 1s;
}
.boo:hover {
  background-color: rgba(0,0,0,.5);
}
.boo:before {
  position: absolute;
  top: 0; right: 0; bottom: 0; left: 0;
  background-color: inherit;
  content: ' ';
}
Run Code Online (Sandbox Code Playgroud)

我在这是要干嘛?

我在这里做的是我在它后面设置一个RGBa background-colordiv在其上background-image转换它background-color(它的alpha):hover.所有这一切发生后面background-image.然而,我也使用background-color: inherit伪元件,这意味着,在任何给定时刻,伪元件,这是位于它的父上面上div(并因此上述background-imagediv)都将有相同的background-color(这意味着background-color伪元素将从转换rgba(0,0,0,0)rgba(0,0,0,.5)on :hover).


为什么这样?

我没有直接background-color转换伪元素的原因是对伪元素的转换的支持仍然不是那么好.

支持伪元素的转换

✓Firefox支持伪元素的转换,并支持它们很长一段时间,让我们首先解决这个问题.

当前版本的SafariOpera不支持伪元素的转换.

Chrome仅支持从版本26开始的伪元素转换.

IE10以一种奇怪的方式支持它们,这意味着:

.boo:before { color: blue; transition: 1s; }
.boo:hover:before { color: red; }
Run Code Online (Sandbox Code Playgroud)

不起作用,你必须在元素本身上指定悬停状态.像这样:

.boo:hover {}
.boo:before { color: blue; transition: 1s; }
.boo:hover:before { color: red; }
Run Code Online (Sandbox Code Playgroud)

有关如何使用此inherit技术转换伪元素的各种属性的更多信息和示例:http://vimeo.com/51897358


编辑

直接在伪元素上的转换现在支持Opera,因为从6.1开始切换到Blink和Safari.

  • 这是一个非常巧妙的解决方案!我建议指定transition属性,以便在页面加载时不对元素进行动画处理:`transition:background-color 1s;`. (2认同)
  • 我很高兴看到仍然有人在他们的代码上提供解释:)良好的做法,保持良好的工作! (2认同)

Pev*_*ara 5

虽然@Ana技术也很好,而且工作正常,允许我略微改变我对前一个问题的回答,并在该代码中添加转换. http://jsfiddle.net/Pevara/N2U6B/2/

#the-div {
    width: 500px;
    height: 500px;
    background: url(http://placekitten.com/500/500) no-repeat center center;
    position: relative;
}

#the-div:after {
    content: ' ';
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    background-color: rgba(0,0,0,0);
    transition: background-color .5s;
}
#the-div:hover:after {
    background-color: rgba(0,0,0,.5);   
}
Run Code Online (Sandbox Code Playgroud)

我所做的是我:after在div的默认状态下定义了伪元素,而不仅仅是在悬停状态,而是具有完全透明的背景,以及背景颜色的过渡.在div的悬停时,我将伪元素的背景颜色更改为透明度较低.由于过渡,它很好地消失了.

这项技术与@Ana所做的基本相同,但也许更直观,因为我没有使用background-color: inherit;.此外,如果div会变得比背景图像大,你就不会在边缘上得到"双重黑暗",如http://codepen.io/anon/pen/cjoHr对比这里http://jsfiddle.net/Pevara/N2U6B/3 /