Reducing the opacity on a div without reducing the

2019-06-27 02:43发布

问题:

Want to reduce the opacity of page contents container background without reducing the opacity of the contents.

<div id="container">
   <div id="page contents">
   page contents goes here, like amazing articles and all that.
   </div>
</div>

Needs to be able to expand with the content, thus can't have a fixed height.

Absolute positioning it underneath the content will mean there will be no relationship between the two divs and it wont expand with the contents, so I think this is a dead end, feel free to say otherwise.

Can't use Jquery as could be too laggy and not instant. Other options preferred please.

May have to use 'png' background images but were hoping not to as it is a template and needs to be able to change colour based on colour schemes.

Could generate images on demand but not ideal.

Oh and to top it off cant use CSS3 as wont work in IE! of course!

Any suggestions?

回答1:

My first impulse is a transparent PNG.

But looking further and especially with your comment on variable colour schemes, perhaps hooking into RGBA support would work for you. There's a nice post on it (including how to hack around IE - which doesn't support it at all) here:

http://css-tricks.com/rgba-browser-support/



回答2:

not tested yet, but you get the idea.

<div id="container">
   <div id="page contents">
   <div id="opacity"></div>
   page contents goes here, like amazing articles and all that.
   </div>
</div>

#page {
   position:relative;
}

#opacity {
   position:absolute; z-index:-1; height:100%; width:100%; background-color:#eee; opacity:.7;
}


回答3:

All content of an element will receive it's opacity value, even if you set the content's opacity to 0, you'll stile have the problem... here's a simple solution that I use:

HTML

<div id="menu_bg"></div> <!-- BG FOR LEFT MENU -->
<div id="menu_header">
  <span class="menu_title2">MENU PRINCIPAL</span>
  <div id="menu_opts">
    <ul id="menu">
      <li id="menu_home"><a href="#">HomePage</a></li>
      <li id="menu_home"><a href="#">Company</a></li>
    </ul>
  </div>
</div>

The CSS:

div#menu_bg {
  position:fixed; top:10px; left:10px; z-index:20000;
  width:200px; height:50px;
  background:#000000;
  /* for IE */ filter:alpha(opacity=60);
  /*CSS3 standard*/ opacity:0.6;
}
div#menu_header {
  position:fixed; top:10px; left:10px; z-index:20001;
  width:200px; height:50px; overflow:hidden; cursor:pointer;
}
div#menu_opts {
  position:absolute; top:60px; left:10px;
  width:200px; height:275px; overflow:hidden;
}

The trick is simple, have a div behind you content and use position and z-index to place it. Then draw another div with the content, over the last one, and use same position but set z-index above. This way, you'll have a background with the desired opacity, and your content since it's on another div, will get just right!



标签: css opacity