The image galleries we are about to explore descend from, and share code with, the earliest, simple, CSS gallery I introduced in this blog: a div with position: relative applied, and absolute positioning applied to images inside it. Both examples – a cross-fade and slideshow effect – use the same basic markup. In a compatible browser, mouseover each image to see an example of the associated effect. The markup for both examples is exactly the same:

<div id="gallery">
	<img src="wooly-sunbonnet.jpg" alt="Wooly Sunbonnet">
	<img src="nettleleaf-sage.jpg" alt="Nettleleaf Sage">

… it is only the CSS that changes between them. Note that for both examples to work, the images must be of the exact same size. It is probably easiest to crop the images to the same dimension using before applying the techniques you see here.

CSS Cross-fade Gallery

The applied CSS, sans vendor prefixes:

div#gallery {
	position: relative;
div#gallery img {
	width: 400px; height: 400px;
	position: absolute;
	left: 0;
	transition: all 2s ease-in-out;
div#gallery img:hover {
	opacity: 0;

Very simply, the position: relative declaration makes the div the baseline origin of any elements with position: absolute set inside it. With the second image stacked upon the first, the :hover and applied transition works to cross-fade the images.

CSS Slideshow Gallery

The slideshow is similar, and again uses images of the same size. The containing <div> now has a set height and width, with any overflow hidden:

div#gallery, div#gallery img {
	width: 400px;
	height: 400px;
	overflow: hidden;
	float: left;
div#gallery img {
	transition: all 2s linear;
div#gallery img:hover,
	div#gallery img:hover + img {
		transform: translate(0, -400px);

The CSS is relatively straightforward: the containing <div> and images inside have the same qualities, so their base styles may be grouped under the first style declaration: float applied to the images removes any trace of a gap between them. Hovering over the first image moves it up 400 pixels (the height of the image) while the paired adjacent selector ensures that the next image moves in the same way, at the same time.

Note that both techniques shown here only work on pairs of images: useful for “before and after” comparisons or as an animated alternative to image swaps and CSS sprites. Transitioning a sequence of images greater than two requires using more advanced code to create a CSS slider.

Photographs by Patrick Coin, licensed under Creative Commons.

Enjoy this piece? I invite you to follow me at to learn more.