18
<style type="text/css">
div#foo {
    background: #0000ff;
    width: 200px;
    height: 200px;

    opacity: 0.30;
    filter: alpha(opacity = 30);
}
div#foo>div {
    color: black;
    opacity:1;
    filter: alpha(opacity = 100);
}
</style>

<div id="foo">
    <div>Lorem</div>
    <div>ipsum</div>
    <div>dolor</div>
</div>

In the above example, the opacity of div#foo is inherited by child elements, causing the text to become nearly unreadable. I suppose it's wrong to say it is inherited, the opacity is applied to the parent div and the children are part of that, so attempting to override it for the child elements doesn't work because technically they are opaque.

I typically just use an alpha png background image in such cases, but today i'm wondering if there's a better way to make a background of a div semi-transparent without affecting the contents.

4

3 回答 3

39

您可以使用rgba()

div#foo
{
    background: rgba(0, 0, 255, 0.3);
}

要使其在旧 Internet Explorer 中工作,请使用CSS PIE。有一些限制,但这些限制以向后兼容的方式处理:RGB 值将被正确渲染,不透明度将被忽略。

于 2010-04-01T15:23:25.800 回答
7

最好的方法是将透明png设置为背景..

于 2010-12-15T14:10:42.903 回答
5

如果使用不透明度,则必须将它们放在单独的 DIV 中,然后将它们排列在一起。背景 DIV 将具有较低的不透明度,而前景 DIV 将使您的内容具有 100% 的不透明度。

于 2010-04-01T15:34:07.070 回答