CSS背景透明,文本完全可见

4
我想实现这样的效果:一个div有透明背景色(这样我就可以看到后面的图像),并保持网站主要内容居中(即使调整窗口大小)。
我在JS Fiddle中写了一个快速模拟以展示我的尝试。我遇到的问题是,当我将根div的不透明度设置为0时,每个子元素都会获得该不透明度,我无法覆盖它。我知道在fiddle中的做法由于没有固定内容而不起作用,但是如何实现这种效果并在调整窗口大小时保持网站居中?
我能否不使用JS来完成这个效果?
最后一点,在JS Fiddle中,文本应该是不透明的1,而黄色应该保持不透明度0.3。
以下是JS Fiddle:http://jsfiddle.net/7d6NY/ HTML:
    <img src="https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcQuK9zPKC8rFhpf1S9-2bGCaIUdm9-YMeQiBRdc5rRY_xiQTYvd" alt="image missing" class="bg-image" />
<div class="transparency">
    <div class="content">
        THIS IS MY PAGE CONTENT
    </div>
</div>

CSS:

    .transparency{
    background-color: yellow;
    display: block;
    opacity: 0.3;
    margin: 0 auto;
    width: 300px;
    height: 500px;
}
.content{
    color: #000;
    opacity: 1;
    text-align: center;
}
img{
    /* Set rules to fill background */
    min-height: 100%;
    min-width: 1920px;
    /* Set up proportionate scaling */
    width: 100%;
    height: auto;
    /* Set up positioning */
    position: fixed;
    top: 0;
    left: 0;   
}
3个回答

3

使用“RGBA”值的背景颜色对你有帮助吗?

.content{
    background-color:rgba(255,255,0,0.3);
    color: #000;
    opacity: 1;
    text-align: center;
}

3
您可以使用 rgba (MDN上的更多信息) 值来设置透明背景颜色,同时不要忘记为图像赋予负的z-index值,以便它位于内容后面:

演示

CSS :

.transparency{
    background-color: rgba(255, 255, 0, 0.3); /* <-- this line is modified */
    display: block;
    margin: 0 auto;
    width: 300px;
    height: 500px;
}
.content{
    color: #000;
    text-align: center;
}
img{
    /* Set rules to fill background */
    min-height: 100%;
    min-width: 1920px;
    /* Set up proportionate scaling */
    width: 100%;
    height: auto;
    /* Set up positioning */
    position: fixed;
    top: 0;
    left: 0;  
    z-index:-1; /* <-- this line is added */
}

使背景颜色:rgba(252,252,0,0.3)生效的条件是什么? - Bagzli
1
@Bagzli 没有特定的条件,你可能想知道 rgba 颜色在 IE8 中不受支持,就像透明度一样。http://caniuse.com/css3-colors - web-tiki

1
.transparency {
background-color: rgba(255, 255, 0, 0.4);    
display: block;
margin: 0 auto;
width: 300px;
z-index: 10000;
position: relative;
height: 500px;
}

.content {
color: #000;
text-align: center;
}

这里有一个工作演示; http://jsfiddle.net/7LNS4/


我已经更新了我的代码,请尝试一下,在js fiddle中可以运行。 - Jay

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接