如何使用CSS在div中为背景图像和文本进行不同的过渡

时间:2014-12-29 15:39:15

标签: html css css3

我正在尝试实现过渡效果,就像在本网站的img / links中一样:verena michelitsch

这是我到目前为止所尝试过的:

HTML:

<div id="centerpiece">
  <div id="photography"><a href="photography.html">Photography</a></div>
  <div id="painting"><a href="painting.html">Paintings</a></div>
  <div id="sketches"><a href="sketches.html">Sketches</a></div>
  <div id="digitalpainting"><a href="digitalpainting.html">Digital Paintings</a></div>
</div>

CSS:

#centerpiece div {

    border: 10px solid gray;
    border-radius: 100%;
    background-image: url(images/viraj.jpg);
    line-height: 300px;
    text-align: center;
    vertical-align: middle;
    opacity: 1;
    transition: opacity 0.5s ease-in-out;
    -moz-transition: opacity 0.5s ease-in-out;
    -webkit-transition: opacity 0.5s ease-in-out;

}

#centerpiece div a {
    display: block;/*to extend to div boundary*/
    height: 300px;
    border-radius: 100%;
    font-family: Existence Light, Aaargh, Arial, Helvetica, sans-serif;
    font-size: 30px;
    font-weight: 700;
    text-decoration: none;
    color: white;
    text-transform: uppercase;
    opacity: 0;
    transition: opacity 0.5s ease-in-out;
    -moz-transition: opacity 0.5s ease-in-out;
    -webkit-transition: opacity 0.5s ease-in-out;
}

#centerpiece div:hover {
    opacity: 0.5;
}

#centerpiece div a:hover {
    opacity: 1;
}

虽然文本的转换(在a元素内)发生,但它的opacity属性最终设置为0.5而不是1,即使它应该为我编写{{{1}的CSS规则1}} #centerpiece div a之后。

如何使最终#centerpiece div等于1?

1 个答案:

答案 0 :(得分:1)

您在悬停时将opacity的{​​{1}}设置为#centerpiece div,并且它是您的0.5标记的父级。父母的a会影响其子女,因此当您在opacity上呼叫1时,它仍会从其父级继承#centerpiece div a。您可以将opacity: 0.5设置为#centerpiece div以开始并增加到1.或者您可以使用0.5(尽管如果您有图像rgba则不会影响不透明度)

FIDDLE

<强>更新

考虑到你当前的小提琴,这是一种更有效的方法:

HTML

rgba

CSS

<div class="container">
  <div class="overlay"><a href="#">Photography</a></div>
</div>

2nd FIDDLE

NEW UPDATE

您在their示例中看到的并不是您的想法。如果你检查他们的代码,你会看到他们根本没有淡出背景,他们使用内联样式(可能是从数据库看起来是动态的)来添加一个颜色,该颜色匹配每个图像的低不透明度,因为{{ 1}}。因此,如果我不得不猜测我会说当他们上传图像时,他们还会添加一个颜色十六进制,然后将其用作叠加层。 (我检查了它们的叠加层,它们不仅都是内联的,这通常是动态代码的标志,但颜色都不同)。在这个最新的小提琴中,你会看到我完全按照自己的意愿行事。当你悬停时褪去背景,但结果与我的第二小提琴相似,但可能不是你期望的那样:

3rd FIDDLE

为了证明我说的是什么,我把他们的形象和他们用来做这个的颜色和我的小提琴重新创造出来。我所要做的只是交换图像和我用于.container{ background: url("http://www.placecage.com/400/200") no-repeat; width: 400px; height: 200px; } .container:hover .overlay{ opacity: 1 } .overlay{ opacity: 0; background: rgba(255,255,255,.8); width: 100%; height: 100%; text-align: center; transition: all 0.5s ease-in-out; -moz-transition: all 0.5s ease-in-out; -webkit-transition: all 0.5s ease-in-out; } a{ display: inline-block; font-family: "Arial"; font-size: 24px; color: #000; text-decoration: none; text-transform: uppercase; text-align: center; line-height: 200px; } 背景的颜色(来自小提琴2):

RECREATION FIDDLE