Callum Linington
Callum Linington

Reputation: 14417

CSS Specific Opacity Application

I've made this fiddle, to demonstrate my problem and question.

I want to have the div that holds all the text have an opacity so that you can see the background (for some reason the background won't show up, works on my machine).

However, in my example all the text has got the same opacity, and that isn't useful for reading.

So basically, how do you have full opaque text, I assume that any child elements will be set to the opacity setting of the parent?

html:

<div class="mainPage">
    <h1>Welcome</h1>

    <p>... some text ...</p>
</div>

css:

.mainPage {
    opacity:0.6;
}

Upvotes: 0

Views: 63

Answers (3)

Bohdan Yurov
Bohdan Yurov

Reputation: 360

Opacity affects whole element, so there is no way to do that just using "opacity".

You may set RGBA color to background (last argument is opacity), use transparent BG image or create another div (wrapper) with opacity.

If you need support old browsers, see fiddle with wrapper: http://jsfiddle.net/nick4fake/N78G8/

<div class="a"><div class="b b2"></div>My text example</div>
<div class="b">My text example</div>

Here b2 is wrapper class.

Also, check this link: http://css-tricks.com/forums/topic/css-transparency-in-wrappers/

Upvotes: 1

Hrvoje Golcic
Hrvoje Golcic

Reputation: 3686

You want to use

.mainPage {
    background:rgba(0,0,0,0.6);
}

where 0,0,0 represent black (255,255,255 would be white then) and 0.6 alpha channel

but it is CSS3 so check for the compatibility. Also if you want to this to work in older versions of IE, you could consider PIE CSS

EDIT: As other have mentioned, there are other solutions possible here. To use repeating transparent 1x1px image as your background (which will not work in IE6 if you care?), there are also some php scripts to include to your css that will generate those images automatically for you.

Or another solution would be to use another div with opacity and position it absolutely behind your content, so that div wouldn't contain your content but anyway would be behind.

Upvotes: 2

Matthew
Matthew

Reputation: 2310

Two possibilities:

  1. Use rgba colours:

    background-color:rgba(255,255,255,0.6);
    

    Though you'll want to check the compatibility of this, as it's CSS3. The only browsers that it doesn't work in are Internet Explorer 6, 7, and 8 (and less), so you might be ok using this - it works in all other major browsers.

  2. Make a semi-transparent PNG in Paint.NET, Photoshop, or some other similar program, and use that as the background image:

    background-image:url("./myTransparentImage.png");
    

    This has the benefit of working on pretty much every browser, except probably IE6 and the like as it doesn't support alpha transparency.

    You'd probably want to make it a 1px × 1px image, to keep the size down, and then that would tile across the whole element.

Upvotes: 0

Related Questions