Mike Perrenoud
Mike Perrenoud

Reputation: 67898

Layer one DIV over another to provide a transparent background with strong text

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?

Upvotes: 0

Views: 1277

Answers (3)

GreyRoofPigeon
GreyRoofPigeon

Reputation: 18113

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

Upvotes: 1

Sergiy T.
Sergiy T.

Reputation: 1453

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).

Upvotes: 1

user2584008
user2584008

Reputation: 41

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)
}

Upvotes: 1

Related Questions