Setting opacity of background color transparent

Published January 14, 2015 by CSS Newbies.

Opacity is a relatively new feature in CSS and is a great way to make your web pages stand out. Minor things like changing the opacity or adding text shadows look great when done in moderation. There’s two way to set the opacity of a background in CSS. The first is using the rbga property on your background. Just like rbg, you’ll provide your red, blue, and green values with the fourth value being the opacity.

div { 
background: rgb(54, 25, 25); 
background: rgba(54, 25, 25, .5); 
}

The text above will provide a 50% opacity. Changing the .5 to 1.0 would be fully opaque (not transparent). It is a good idea to add the rbg above the rbga like I have done for older browsers that do not support rbga.

The second way to set the opacity of a background is to use the opacity property in CSS. There only issue with this method, is the opacity property sets the opacity for the entire element including any text or images in it. We can work around this by nesting our elements inside each other like below.

#container { position: relative; width: 300px; height: 200px; } 

#bg { 
background: #CCC;
filter:alpha(opacity=60); /* IE */
-moz-opacity:0.6; /* Mozilla */
opacity: 0.6; /* CSS3 */
position: absolute; top: 0; left: 0; height: 100%;
width:100%;
}

#text { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
<div id="container">
<div id="bg"></div>
<div id="text">Test</div>
</div>

8 Responses

  1. Pingback: How to capitalize letters using CSS | Lunarium Design

  2. Pingback: How to Manage Your Webpage’s Layout with CSS | Lunarium Design

  3. Pingback: Opacity of background color – Relatris' WordPress Tools and Techniques

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>