首页 文章

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

提问于
浏览
14

今天早些时候我问了Overlay a background-image with an rgba background-color . 我的目标是使用背景图像的div,当有人悬停div时,背景图像会覆盖rgba颜色 . 在the answer中,给出了 :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添加淡入淡出效果?

2 回答

  • 5

    对的,这是可能的 .

    演示

    .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 后面,并在 :hover 上转换 background-color (它的alpha) . 所有这些都发生在 background-image 之后 . 但是,我也在伪元素上使用 background-color: inherit ,这意味着,在任何给定时刻,位于其父级 div 之上(因此位于 divbackground-image 之上)的伪元素将具有相同的元素 . background-color (意味着伪元素的 background-color 将在 :hover 上从 rgba(0,0,0,0) 过渡到 rgba(0,0,0,.5) ) .


    为什么这样做?

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

    支持伪元素的转换

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

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

    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 .

  • 28

    尽管@Ana技术也很好,并且工作正常,允许我稍微改变我对previous question的回答,并在该代码中添加转换 . 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);   
    }
    

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

    该技术与@Ana所做的基本相同,但可能更直观,因为我不使用 background-color: inherit; . 此外,如果div会变得比背景图像大,你就不会在边缘得到'double darkness',如此处所示http://codepen.io/anon/pen/cjoHr对比这里http://jsfiddle.net/Pevara/N2U6B/3/

相关问题