开发者

How do I get a translucent background with opaque text?

I'm trying this method, I just put 2 divs, I style the first adding the background and making it translucent and I style the first to make it opaque:

This is the code:

<div id="container">
    <div id="opaquetext">
      This is a normal text
      on a translucent background
    </div>
</div>

And CSS:

   #container {
       back开发者_如何转开发ground-color: #ffffff;  /* the background          */
       filter:alpha(opacity=50);   /* Internet Explorer       */
       -moz-opacity:0.5;           /* Mozilla 1.6 and below   */
       opacity: 0.5;               /* newer Mozilla and CSS-3 */
    }
    #opaquetext {
       filter:alpha(opacity=100);  /* discarded */
       -moz-opacity:1.0;           /* discarded */
       opacity: 1.0;               /* discarded */
    }

I thought it would work but for some reason it renders the text transparent too.


Opacity styles affect the display of an entire element - both its background and foreground colors. The styles are also multiplied down a tree of elements. In other words, your inner div is simply being styled to have 100% opacity of the outer div. 100% of 50% opacity means it displays at the same opacity as the parent element: 50%.

There are two workarounds, neither of which require two divs, both of which allow you to specify color: #000000 for your text as usual:

  • Use a transparent background image
    IE does not support this before IE7

  • Use background-color: rgba(255, 255, 255, 0.5)
    IE does not support this before IE9, Firefox does not support this before 3.5


Specify the backgrounds using rgba() instead of #... or rgb() where the last argument in rgba denotes the opacity of background. Opacity is for defining the opacity of whole element. Eg:

background: rgba(255, 0, 0, 0.2)

More info about this: http://www.css3.info/preview/rgba/

But it may raise compatibility issues with old browsers and ie. If you want to support older browsers you should consider using transparent background image as specified in boltclock's answer.


Opacity inheriting is the standard behavior of all browsers. If you want the child div dis-inherited on opacity, you have two choices:

  1. using absolute position in #opaquetext's style:

    #opaquetext {
        position: absolute;
        top: 10px;
        left: 10px;
        filter:alpha(opacity=100);  /* worked */
        -moz-opacity:1.0;           /* worked */
        opacity: 1.0;               /* worked */
    }
    
  2. using photo/image software to make a background with the desired opacity, and drop opacity setting in css.

ref:

  • http://www.impressivewebs.com/css-opacity-that-doesnt-affect-child-elements/
  • http://www.wickham43.supanet.com/~wickham43/tutorial/opacity.html
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜