简体   繁体   English

CSS不透明度和子元素

[英]CSS opacity and child elements

<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. 在上面的示例中, div#foo的不透明度由子元素继承,导致文本几乎不可读。 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. 我认为说它是继承的是错误的,不透明度应用于父div而子节点是其中的一部分,因此尝试为子元素覆盖它不起作用,因为从技术上讲它们是不透明的。

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. 我通常只是在这种情况下使用alpha png背景图像,但今天我想知道是否有更好的方法来使div半透明的背景而不影响内容。

You may use rgba() . 你可以使用rgba()

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

To make it work in old Internet Explorers use CSS PIE . 要使它在旧的Internet Explorer中工作,请使用CSS PIE There are some limitations , but those are handled in a backwards compatible way: the RGB value will be rendered correctly and the opacity will be ignored. 存在一些限制 ,但这些限制是以向后兼容的方式处理的:RGB值将正确呈现并且不透明度将被忽略。

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

If you use opacity, you'd have to put them in separate DIV's and then line them up together. 如果使用不透明度,则必须将它们放在单独的DIV中,然后将它们排成一行。 The background DIV would have the lower opacity, and foreground DIV would have your content with 100% opacity. 背景DIV的不透明度较低,前景DIV的内容为100%不透明度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM