且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我可以只为 div 的背景图像设置不透明度吗?

更新时间:2022-10-19 13:35:11

不,这是不可能的,因为 opacity 会影响整个元素,包括其内容,并且没有办法改变这种行为.您可以使用以下两种方法解决此问题.

二级div

向容器中添加另一个 div 元素以保持背景.这是跨浏览器最友好的方法,甚至可以在 IE6 上运行.

HTML

<div class="bg"></div>你好呀

CSS

.myDiv {位置:相对;z-索引:1;}.myDiv .bg {位置:绝对;z-索引:-1;顶部:0;底部:0;左:0;右:0;背景: url(test.jpg) 中心居中;不透明度:.4;宽度:100%;高度:100%;}

参见 jsFiddle 上的测试用例

:before 和 ::before 伪元素

另一个技巧是使用 CSS 2.1 :before 或 CSS 3 ::before 伪元素.:before 伪元素从版本 8 开始在 IE 中被支持,而 ::before 伪元素根本不被支持.这有望在版本 10 中得到纠正.

HTML

你好呀

CSS

.myDiv {位置:相对;z-索引:1;}.myDiv:之前{内容: "";位置:绝对;z-索引:-1;顶部:0;底部:0;左:0;右:0;背景: url(test.jpg) 中心居中;不透明度:.4;}

附加说明

由于 z-index 的行为,您必须为容器设置一个 z-index,并为背景图像设置一个负的 z-index.

测试用例

在 jsFiddle 上查看测试用例:

Let's say I have

<div class="myDiv">Hi there</div>

I want to put a background-image and give it an opacity of 0.5 – but I want that the text I have written will have full opacity (1).

If I would write the CSS like this

.myDiv { opacity:0.5 }

everything will be in low opacity – and I don't want that.

So my question is – How can I get low-opacity background image with full opacity text?

Nope, this cannot be done since opacity affects the whole element including its content and there's no way to alter this behavior. You can work around this with the two following methods.

Secondary div

Add another div element to the container to hold the background. This is the most cross-browser friendly method and will work even on IE6.

HTML

<div class="myDiv">
    <div class="bg"></div>
    Hi there
</div>

CSS

.myDiv {
    position: relative;
    z-index: 1;
}

.myDiv .bg {
    position: absolute;
    z-index: -1;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: url(test.jpg) center center;
    opacity: .4;
    width: 100%;
    height: 100%;
}

See test case on jsFiddle

:before and ::before pseudo-element

Another trick is to use the CSS 2.1 :before or CSS 3 ::before pseudo-elements. :before pseudo-element is supported in IE from version 8, while the ::before pseudo-element is not supported at all. This will hopefully be rectified in version 10.

HTML

<div class="myDiv">
    Hi there
</div>

CSS

.myDiv {
    position: relative;
    z-index: 1;
}

.myDiv:before {
    content: "";
    position: absolute;
    z-index: -1;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: url(test.jpg) center center;
    opacity: .4;
}

Additional notes

Due to the behavior of z-index you will have to set a z-index for the container as well as a negative z-index for the background image.

Test cases

See test case on jsFiddle: