在CSS中更改背景图像的不透明度

4

我是一位有用的助手,可以为你翻译文本。

我看到了一些类似的问题。但我的方法不同,那些方法都不适用于我。这就是为什么我要发布这个问题。

我想在不改变子元素不透明度的情况下改变背景图像的不透明度,其中背景图像加载在body标记内。

html:

<body>
    <div id = "background-div">
        <div class = "header">
            <div class = "ham-icon">
                <img src = "images/ham-icon.png">
            </div>
            <div class = "logo">
                <span class = "google-logo">Google</span><span class = "hangouts-logo"> Hangouts</span>
            </div>
            <div class = "profile-data">
            </div>
        </div>
        <div class = "body">
        </div>
    </div>
</body>

CSS:

body
{
    position: relative;
    background: url(../images/back1.jpg) no-repeat center center fixed; 
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

1
你能否创建一个 jsfiddle 或 plnkr? - martin
1
你可以使用伪元素并将背景设置为它。请参见https://dev59.com/Zmcs5IYBdhLWcg3wwmnA#12606407 - Mikhail Romanov
@Martin,我解决了。谢谢。 - ONE_FE
4个回答

13

使用BODY滤镜的HTML背景

<HTML> 具有背景图像,而<body> 则具有50%透明度的白色(使用RGBA实现透明色层)。

html, body {
  height:100%;
  padding: 0;
  margin: 0;
}

html {
  background:url(https://i.ytimg.com/vi/qOfuTI5165w/maxresdefault.jpg) no-repeat center center fixed;
}

body {
  background:rgba(255,255,255,0.5); /* applies a 50% transparent white background */
}


使用 CSS 伪选择器 :before 来为 body 元素添加样式

另一种方法是使用 body 元素的伪选择器,可以创建一个位于实际 body 元素后面的“层”,该层可以应用 opacity 属性而不影响其他元素。


html, body {
  height:100%;
  padding: 0;
  margin: 0;
}

body:before {
  background:url(https://i.ytimg.com/vi/qOfuTI5165w/maxresdefault.jpg) no-repeat center center fixed;
  display: block; content:""; position: absolute; z-index:-1;
  top:0; left: 0; right: 0; height: 100%;
  opacity:.5;
}


3
您可以尝试以下解决方法:
1)使用已经具有alpha通道的图像,例如png;
2)将背景div作为其他元素的兄弟节点而不是父节点,并使用css更改它们的位置,如position:absolute; z-index;等。
3)如果您的图像只包含颜色,则可以保持html不变并使用rgba/css渐变。

1
您可以将背景放在单独的 <div> 中:
<body>
    <div id="content">
        <div id="background-div"></div>
        <!-- content -->
    </div>
</body>

然后定位并设置样式以填充整个内容。
#content {
    positon: relative;
}

#background-div {
    position: absolute;
    width: 100%;
    height: 100%
    opacity: 0.5;
    background: url(...);
}

-2

使用直接子选择器 body > .backgroudimg{ blah blah }


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