如何在CSS中使背景图片变暗?

3

我有一个来自Bootstrap的Jumbotron,我想把它的背景变暗,但不影响输入在其中的文本。有没有办法实现这样的效果?

我已经到处找过,但我找到的所有解决方案都会使文本变暗。

目前为止,我的做法是:

.mainJumbotron {
    margin: 0px;
    height: 250px;
    text-align: center;
    background-image: url(http://i.imgur.com/qj2w73W.png);
    background-repeat: no-repeat;
    background-size: cover;
}
<div class="jumbotron mainJumbotron">
    <h1 style="">Hakkımızda</h1>
</div>


好的,我已经添加了代码。 - Ege Kaan Gürkan
3个回答

7
尝试这样做:
在你的“jumbotron”类中,如果还没有,请添加“position:relative;”以使其具有更多的CSS。这将允许下一步在该框内定位。
然后,添加一个伪元素“:after”,并使用以下CSS:
.jumbotron:after {
    content:"";
    display:block;
    width:100%;
    height:100%;
    background-color:rgba(0,0,0,0.5);
    position:absolute;
    top:0;
    left:0;
    z-index:1 /*Added this in the updated */
}

background-color的阴影由最终值控制。0.5表示50%的不透明度,将其提高至1或降低至0以获得所需的深浅程度。

更新:指出的问题是盒子内的任何内容都被新伪元素覆盖了。这里有一个简单的解决方法。在:after元素中添加z-index:1;,然后添加以下内容。

.jumbotron > * {
    position:relative;
    z-index:2;
}

感谢 cale_b 提供的帮助 https://jsfiddle.net/e8c3ex0h/3/


也不起作用 :( - Ege Kaan Gürkan
尝试将z-index:1或更高的值添加到:after中,以查看它是否在后面。 - ntgCleaner
@EgeKaanGürkan,我已经找到了解决方案,现在正在编辑我的答案。 - ntgCleaner
没错 - 明白了。需要在h1上设置位置才能使z-index起作用。总是忘记这一点... https://jsfiddle.net/e8c3ex0h/4/ - random_user_name
1
@EgeKaanGürkan, 你做到了!不过请查看约翰的答案 - 这似乎是更好的实践。 - ntgCleaner
显示剩余9条评论

1
您可以在CSS中尝试以下内容,以查看是否获得所需的结果。
    #element {
-webkit-box-shadow: inset 0px 50px 100px 0px rgba(0, 0, 0, 1);
-moz-box-shadow: inset 0px 50px 100px 0px rgba(0, 0, 0, 1);
box-shadow: inset 0px 50px 100px 0px rgba(0, 0, 0, 1);
}

不太是我想要的:/ - Ege Kaan Gürkan
所以你想要一个叠加层吗? - RiaanV
我希望将背景图片稍微变暗一些,以便前面的文本可以清晰地阅读。 - Ege Kaan Gürkan
你想调整图像的对比度? - RiaanV
不太对。想象一下一个半透明的黑色矩形放在图像上方。 - Ege Kaan Gürkan
你能给我提供一张截图吗?这样我才能给你正确的答案。 - RiaanV

1
这是如何做到的:

body, h1 {
    margin: 0;
}

.mainJumbotron {
    margin: 0px;
    height: 250px;
    text-align: center;
    background-image: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)),
                      url(http://i.imgur.com/qj2w73W.png);
    background-repeat: no-repeat;
    background-size: cover;
    position: relative;
}

h1 {
    color: #fff;
}
<div class="jumbotron mainJumbotron">
    <h1 style="">Hakkımızda</h1>
</div>

(见 this Fiddle

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