Top

Make Images Transparent Using Only CSS

Posted on March 5, 2009

Transparent Images using CSSMost of the time, when you’re needing to have an image fade slightly or become transparent or opaque, you pop open the photo in Photoshop and lower the Opacity slider. Imagine being able to control the opacity of an image using only a few short lines of CSS.

Well, believe it or not this is easily doable, and it works across multiple browsers as well…though, it might not work through RSS feedreaders; if you’re reading this post through your feedreader, you might want to click through to our site to see the full effects of the transparency.

Step 1 – Modify Your CSS File
We first need a way to control only specific images. In our CSS file, we’ll insert this value:


.transparency {
    filter:alpha(opacity=50);
    opacity:0.5;
}

That’s it! That’s the only code you need to insert into your CSS file. To explain the attributes further:

Filter attribute
– Compatible with Internet Explorer
– The value for Alpha(Opacity) can range from 0 to 100

Opacity attribute
– Compatible with Firefox, Chrome
– The value for Opacity can range from 0 to 1 (where 1 equals 100% opacity)

Step 3 – Modify Your Image Tags
Now let’s look at your page’s content. Inside the <IMG> tag, we’ll need to specify an class of “transparency”, as well as add values for onmouseover and onmouseout.

<img src="/images/opacity_test.jpg" class="transparency" alt="example" onmouseover="this.style.opacity=1;this.filters.alpha.opacity=100" onmouseout="this.style.opacity=0.5;this.filters.alpha.opacity=50" >

example

This code will make the opacity of the image 100% when you mouse-over it, then change it back to to 50% opacity when you mouse moves away.

Step 3 – Method 2: Reverse It!
You can actually reverse the effect by simply modifying your <IMG> tag–no need to specify the id value or change your CSS file!

<img src="/images/opacity_test.jpg" alt="example"
onmouseover="this.style.opacity=0.5;this.filters.alpha.opacity=50" onmouseout="this.style.opacity=1;this.filters.alpha.opacity=100" >

example

Simply adding this code to your image will shift the opacity to 50% on mouse-over and the image returns to full opacity on mouse-out. Below is an example of how the image transparency will work on top of a colored background.

example

Further Reading
Check out Jared’s post on CSS Basics – 5 Steps Toward Mastery.


Keep Reading!

Comments

2 Responses to “Make Images Transparent Using Only CSS”

  1. UpgradeOSX on March 30th, 2011 8:40 pm

    Excellent! Exactly what I was looking for!

  2. Harward on September 1st, 2011 5:35 pm

    Yes! Thank you, you are the only person who has explained it in a way I understand!

Got something to say?





Bottom