demosthenes.info

Independent notes on CSS, SVG, animation and front-end design.

Articles / Article

Animating Sliding Door Images To Reveal A Caption

Using a single photograph

As a general rule, I prefer not to disturb the integrity of a well-crafted photograph when transitioning in a caption. Recently, I’ve seen examples that featured a variation that split the image itself to show hidden text underneath; while it’s not my personal preference, I did see some potential to the technique, together with a few possible improvements to the code. Most methods use PhotoShop to create two different image slices, but it’s much more efficient to do so using CSS.

My version uses three copies of the same image. This has little effect on loading times, as browsers are intelligent enough to cache one copy and use it for any duplicates. One copy of the image is used to size the div container to the correct aspect ratio and dimensions; the others will be split into the top and bottom halves using clip. I’ll also place some text that will be revealed after the image splits in two:

<div id="splitter">
<span>Road To Nowhere</span>
<img src="road-to-nowhere.jpg" alt>
<img src="road-to-nowhere.jpg" alt>
<img src="road-to-nowhere.jpg" alt="Photograph of highway to Uluru, Australia" style="position: static; opacity: 0">
</div>

The initial CSS code:

div#splitter {
position: relative;overflow: hidden;
width: 500px; background: #0057a7;
font-family: Blue Highway, Arial, sans-serif;
color: #fff; margin: 0 auto;
font-size: 0;
}
div#splitter img {
position: absolute;
transition: 1s all ease-in-out;
width: 100%;
}
div#splitter span {
position: absolute; font-size: 8rem;
top: 150px; left: 100px;
}

overflow: hidden conceals the halves of the image as they draw back. To clip and animate the slices, I’ll use an nth-of-type selector:

div#splitter img:nth-of-type(1) {
clip: rect(0px,500px,250px,0px); }
 
div#splitter img:nth-of-type(2) {
clip: rect(250px,500px,500px,0px); }
div#splitter:hover img:nth-of-type(1) {
transform: translateY(-150px); }
div#splitter:hover img:nth-of-type(2) {
transform: translateY(150px); }

The one drawback is that the result is not responsive, as browser support of clip does not yet allow length values in units other than pixels for the property. Aside from that temporary disadvantage, the method shown here yields the same result, with no need for PhotoShop to create different versions of the same photograph.