CSS Image Swap from Image Crop

I’m often asked by clients and coding learners how to conceptualize the output of HTML/CSS to front-end. Basically these are first steps to fully understanding what the DOM hierarchy is — or in other words, how the browser interprets the document flow and order.

A client was keen to create a CSS class that would produce a image swap with an image tag in a blog post. He would create two images and insert them into a DIV that would “hide” one. On hover, the other half of the image would appear. He knew such a thing could happen and that two divs would possibly be involved but could not determine how the CSS would do this.

The solution is to put both images into a div, we’ll call swapimage, and assign the second image class swap-target.  Here the HTML5 figure tag can be used in place of the div as it works semantically.

<figure class="swapimage">
<img src="image1.png" alt="First Image." />
<img src="image2.png" class="swap-target" alt="Second Image." />

And the CSS:

<style type="text/css">
.swapimage {
 display: block;
 position: relative;
 margin: 0;
 padding: 0;
.swap-target {
 position: absolute;
 top: 0;
 left: 0;
 display: none;
z-index: 2;
.swapimage:hover .swap-target {
 display: block; }

Here swapimage acts as a “container” for the image swap.  Relative position allows the second image to absolutely align “over” the other one (set by z-index).  On swapimage:hover, the target image is set to block.   CSS visibility can be used, but I prefer display in most cases, as the difference being it actually removes the element from the page.

More Posts


Hey was this useful? Please consider tipping or subscribing as a member. Even just $1 or $5 can help me improve this content and keep it ad-free.