无法控制div内图像的不透明度

时间:2012-09-04 18:37:53

标签: html css opacity

我希望div内的图像不透明,div要透明。我尝试设置图像和div的不透明度,但它不起作用。

jsFiddle链接:http://jsfiddle.net/2BNEF/10/

我希望图像不透明,文字透明可见。

<div id="targetframe">
    It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes
    <div id="target">
        out. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their defaul
        <img class="myimage" src="http://www4.picturepush.com/photo/a/1365552/480/trucks-photgraphy/asdf-%2858%29.jpg?v0"/>
    </div>
</div>


#targetframe {
    background: none repeat scroll 0 0 black;
    border: 2px inset grey;
    font-family: Verdana,sans-serif;
    left: 0;
    margin: 0;
    overflow: hidden;
    padding: 0;
    position: absolute;
    top: 0;
    opacity: 0.5;
}
#target {
    background: none repeat scroll 0 0 transparent;
    height: 100%;
    left: 0;
    position: relative;
    top: 0;
    width: 100%;
    z-index: 0;
}
.myimage {
    opacity: 1;
}

3 个答案:

答案 0 :(得分:4)

如果你在一个元素上设置opacity,那么该元素的所有后代(孩子,所有孩子的孩子......)都会继承它,你无法做任何事情来阻止它

在这种情况下,您可以使用RGBa背景(rgba(0,0,0,.5)而不是黑色 - DEMO)作为div。 RGBa具有出色的支持 - 唯一不支持它的浏览器是IE8及更早版本,对于那些可以使用filter渐变的浏览器。

答案 1 :(得分:1)

正如@Ana所说,不透明度是由父母的所有子女继承的 您可以组合RGBa并使用

为Div的所有孩子设置不透明度
#targetframe > * {
    opacity: 0.5;
}

指定您的图片必须是不透明的

.myimage {
    opacity: 1;
}

http://jsfiddle.net/2BNEF/15/

答案 2 :(得分:1)

或者只是将容器放在具有所需高度和宽度的绝对定位div中,并定位图像并为图像指定更高的z-index,然后指定所需的不透明度。