How to create a transparent background with CSS

The issue of CSS transparency is overlooked, mainly because it is not part of the current W3C specification — CSS level 2.1, and will render your CSS invalid. But it is achievable, nonetheless. The CSS property opacity is used to set the transparency of an element and will work in most modern browsers, barring IE. For it to work in IE we need employ the use of a filter.

Transparency in action

CSS syntax needed to create transparency

CSS Code:

        opacity:.x [0-1]; /* CSS opacity property */
        filter:alpha(opacity=x)[1-100]; /* For IE */             
        

In each line of code, x denotes the value of the opacity. When using the opacity property x must be a decimal, unless you are aiming for maximum transparency, in which case the value of x would be 1; filter takes a whole number.

To set an opacity of 75%, filter would be set to 75 and opacity would be set to 0.75 or .75. The higher the opacity, the less transparent your object will be; the lower the opacity, the more transparent.

opacity is the standard way to create transparency in CSS, but is only currently supported by CSS3 compatible browsers, such as Firefox, Opera, Chrome and Safari. I would recommend always using filter alongside opacity until IE supports opacity (God knows when that will be).

Click here for more information on IE's filter property.

Working Example

The above may have sounded quite confusing...and examples always help, so here is an example where a div is being reduced to a 50% transparency.

CSS Code:


        #box {
            border:2px solid black;
            background:orange;
            height:100%;
            overflow:auto;
            width:160px;
            padding:6px;
            filter:alpha(opacity=50);
            opacity: 0.5;        
        }
       

(X)HTML Code:

        <div id="box">
        <p>Tyger Tyger, burning bright,<br />
        In the forests of the night:<br />

        What immortal hand or eye,<br />
        Could frame thy fearful symmetry?</p>
        </div>
        

Resut:

Tyger Tyger, burning bright,
In the forests of the night:
What immortal hand or eye,
Could frame thy fearful symmetry?

— The Tyger by William Blake

Here's what the above example would look like without the transparency applied to it.

Tyger Tyger, burning bright,
In the forests of the night:
What immortal hand or eye,
Could frame thy fearful symmetry?

Drop me a line

Got any questions? Get in touch via the contact form or email me @ helen@alternategateways.com.

Related Tutorials

Latest Tutorials

View all tutorials

Share/Save
Visit Alternate Gateways on Facebook