CSS3 Fade Effect
Mar 27, 2012 | In CSS, Tutorials |Today, I’ll be showing how to create an awesome CSS3 hover effect that is normally done with javascript. This one is particularly useful for masonry layouts and image galleries.
You’ll need to download the files if you want the images in the demo, or you can just dig up some of your own images.
HTML
The HTML here is extremely basic, with just a container element and 9 images inside.
<section id="images"> <img src="images/1.jpg"> <img src="images/2.jpg"> <img src="images/3.jpg"> <img src="images/4.jpg"> <img src="images/5.jpg"> <img src="images/6.jpg"> <img src="images/7.jpg"> <img src="images/8.jpg"> <img src="images/9.jpg"> </section>
This is all you need.
CSS
The CSS is where it gets a bit more interesting. First of all, we have to style the container div so that it sits in the center of the page.
#images { width: 600px; margin: 0 auto; margin-top: 50px; } 1 We'll need to add some basic styles to the "img" element. 1 #images img { float: left; opacity: 0.8; -webkit-transition: all 400ms ease; -moz-transition: all 400ms ease; -ms-transition: all 400ms ease; -o-transition: all 400ms ease; transition: all 400ms ease; }
Each image has a lower opacity to start off with and will animate its properties. The “float: left” is just for layout purposes.
Now, we have to actually create the CSS effect itself. Here’s how this works: When we hover over the #images container, we’ll style all of the images inside to animate to a lower opacity. We’ll also add a hover style to the “img” element so that its opacity becomes higher. This way, the hovered image will be the focus of the page.
#images:hover img { opacity: 0.7; } #images img:hover { opacity: 0.85; } #images:active img{ opacity: 0.65; } #images img:active { opacity: 0.9; }
As you can see, there are 4 different states for an image: Default, hovered, when another image is hovered, and active.
This creates an interesting effect, and with only CSS3! This method is also useful because it gracefully degrades in older browsers. Users with older browsers won’t get the cool effect, but they will still have all the functionality.