[英]Overlay a background-image with an rgba color, with a CSS3 transition
今天早些时候,我问过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);
}
我现在想要一样,但是有一个CSS过渡:我希望背景颜色淡入。我尝试添加transition: all 1s;
#the-div
CSS,但是没有用。 我也尝试将它添加到#the-div:hover
和#the-div:after
,但这也不起作用。
有没有一种纯粹的CSS方法来为带有背景图像的div添加淡入淡出效果?
对的,这是可能的。
.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: ' ';
}
我在这里做的是我在div
上设置RGBa background-color
,在其background-image
后面并将此background-color
(其alpha)转换为:hover
。 所有这些都发生在 background-image
背后 。 然而,我也使用background-color: inherit
伪元件,这意味着,在任何给定时刻,伪元件,这是位于它的父上述上div
(并因此上述的background-image
的的div
)将具有相同的background-color
(意味着伪元素的background-color
将从rgba(0,0,0,0)
为rgba(0,0,0,.5)
:hover
)。
我没有直接转换伪元素的background-color
是对伪元素的转换的支持仍然不是那么好。
✓Firefox支持伪元素的转换,并支持它们很长一段时间,让我们首先解决这个问题。
✗当前版本的Safari和Opera不支持伪元素的转换。
Chrome仅支持从版本26开始的伪元素转换。
IE10以一种奇怪的方式支持它们,这意味着:
.boo:before { color: blue; transition: 1s; }
.boo:hover:before { color: red; }
不起作用,你必须在元素本身上指定悬停状态。 像这样:
.boo:hover {}
.boo:before { color: blue; transition: 1s; }
.boo:hover:before { color: red; }
有关如何使用此inherit
技术转换伪元素的各种属性的更多信息和示例: http : //vimeo.com/51897358
直接在伪元素上的转换现在支持Opera,因为从6.1开始切换到Blink和Safari。
虽然@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);
}
我所做的是我定义了:after
div的默认状态:after
伪元素,而不仅仅是在悬停状态,而是具有完全透明的背景,以及背景颜色的转换。 在div的悬停时,我将伪元素的背景颜色更改为透明度较低。 由于过渡,它很好地消失了。
这项技术与@Ana所做的基本相同,但也许更直观,因为我不使用background-color: inherit;
。 此外,如果div会变得比背景图像大,你就不会在边缘得到“双重黑暗”,如http://codepen.io/anon/pen/cjoHr对比这里http://jsfiddle.net / Pevara / N2U6B / 3 /
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.