0

What I want to do is have a div with a transparent background that doesn't affect the text. Consider the following HTML:

<section class="content">
    <header>
        <h1>Description</h1>
    </header>
    Code
</section>

If I were to give it the following CSS:

background-color: #7ac0da;
opacity: 0.5;
filter: alpha(opacity=50);

The text would suffer from the transparency of the section. So, I started trying to layer the content like this:

<div class="code-sample">
    <div class="background"></div>
    <section class="content">
        <header>
            <h1>Description</h1>
        </header>
        Code
    </section>
</div>

However, with an enumerable number of iterations I'm unable to get the section to layer over the div. I'll be honest, I've tried positioning the inner div and section absolute and relative. I've tried using the z-index. But really, I'm just shooting in the dark here. I'd like the .background to have a transparent look:

background-color: #7ac0da;
opacity: 0.5;
filter: alpha(opacity=50);

but yet the .content then overlay that div. This will allow me to then float the .code-sample div and do like a three-column layout with those.

How can I achieve what I'm looking for?

Mike Perrenoud
  • 66,820
  • 29
  • 157
  • 232

3 Answers3

1

Use RGB color to only set the transparency for the background:

.class {    
   /* Fallback for web browsers that don't support RGBa */
   background-color: rgb(0, 0, 0);
   /* RGBa with 0.6 opacity */
   background-color: rgba(0, 0, 0, 0.6);
   /* For IE 5.5 - 7*/
   filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000);
   /* For IE 8*/
   -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000)";
}

Source

Community
  • 1
  • 1
GreyRoofPigeon
  • 17,833
  • 4
  • 36
  • 59
1

No need for the extra background div, use RGBA values on .section to get a semi-transparent background which doesn't affect child elements

.content {
background: rgba(0, 0, 0, 0.2)
}
1

Using RGBa sometimes gives rough edges in texts in Firefox. So it may be better in some cases to use semi-transparent png as background (may use data-uri).

Sergiy T.
  • 1,433
  • 1
  • 23
  • 25