May 19th, 2019

Folding the DOM

In my day-to-day life as a front-end developer, I generally treat CSS as a collection of 2D layers. Other than reordering them using z-index, I don't often move things in 3D space.

And yet, for years now, browsers have bundled in a surprisingly capable 3D CSS engine! Someone even built an experimental first-person shooter prototype using it 😮

Believe it or not, this is just a collection of textured divs! View LiveView Live

Today I'd like to leverage that 3D engine to perform a neat trick: folding up an image.

Here's what we'll be building. Check out how this beautiful neon photobeautiful neon photo by Francois Hoang is revealed through a 3D fold animation:

A neon alley with a Chinese sign
This is an interactive demo! Try dragging the slider on the right.

This effect could be useful in a number of scenarios:

  • As a preloader for images. They unfold once they're ready, and the folded copy could use a much-lower-res base64-encoded version!
  • As an on-mount animation when clicking to view an image, to add whimsical charm to an otherwise common feature.
  • For JS game development

This tutorial is React-specific, but the concepts can easily be ported to vanilla JS/CSS, as well as other front-end frameworks.

This is Part I of a two-part series. In the next part, we'll look at how to generalize this effect to work on any DOM node, not just images.

The Trick

Unfortunately, the DOM has no primitive for this; you can't actually fold a DOM node in two.

Instead, we need to be sneaky; we'll use two images, and set them up so that it appears like a single image.

Each image is set to take up 50% of the real height, and then the bottom image has its background-position shifted up

background-position: '0 0%'
Offset

Pretty convincing, right? By juxtaposing the same image twice, and tweaking the offset of the background image, we're able to give the impression of a single image.

To fold the bottom image up, we'll need to make use of a few CSS properties. This post will explain this technique in depth, but those who just want to see the code can find it on Githubon Github.

Transform

Transform is our gateway to all sorts of effects. With transform, we can move stuff around, scale it larger and smaller, skew it, or rotate it.

In our case, we want to use a rotation, along the X axis:

transform: rotateX(0deg)
cats in a basket
Axis
Degrees
Perspective

By default, transforms still look very "2d". The rotations above don't look quite right, since objects closer to the viewer should look larger.

The solution to this is to apply a "perspective" property to the parent container. The value is given in px, and represents the distance that the viewer is from the item being transformed. The smaller the number, the more intense the transform effect.

perspective: 500px
cats in a basket
Perspective
Transform Origin

By default, rotations assume that you want to spin the items around their center point. The transform-origin property allows us to change the pivot point for rotation (and for all other transforms as well!)

Try changing it from the default "center" value to "top" or "bottom".

transform-origin: center center;
cats in a basket
Y
Our MVP

With all those pieces, we can achieve a "minimum viable product" for this effect. Here's what we get when we combine them:

With a little bit of CSS and a sprinkle of React state, we have the fundamental effect we're after!

Accessibility

There's a subtle problem to this solution: images are meant to have alt tags, for users using screen readers. There is no way to specify an alt tag for a <div> with a background image. By using a background-image, we make this image invisible to assistive technologies.

Happily, there's an easy solution. Let's use a real <img> tag for the top half of our folding element. In order to prevent the whole image from showing, we'll put it in a half-height div with overflow: hidden.

Here's what this looks like:

Adding whimsical details is great, but not when it comes at the expense of accessibility.

Polishing

You may have noticed, though, that it's missing some of the bells and whistles of the original demo. Let's flesh some of these out.

Adding a backface

In our original demo, the "back" of the card has a slightly-transparent white background. The idea is to make it seem like a slightly-seethrough piece of paper.

Let's tackle this problem in isolation at first, and then we can add it in to our full demo.

First, we need a new div, with a nearly-opaque white background. We'll position this in the same place as our card:

Next, we need to make sure that this div is only shown when the card is facing the viewer. Happily, CSS has an elegant way to handle this scenario, built right into the language!

We need to learn about a couple more properties.

Backface Visibility and Transform Style

The backface-visibility property allows us to specify whether an item should be visible when it's rotated more than 90 degrees in either direction.

In this case, we also need to add transform-style: preserve-3d to the parent element (the one responsible for the animation). This property allows elements to be positioned in 3D space, and it allows backface-visibility to work correctly in this context.

Eagle-eyed readers—or, those who can read Chinese—might've noticed that this effect is backwards. Right now, we only see our white "back" when the card is facing forwards!

It makes sense, because both the card and the backside are facing the same way. We're only hiding the backside when the whole thing is rotated around.

We can fix this by being a little sneaky, and giving our backside element a 180-degree Y-axis rotation. Think of it like stacking two playing cards, and then flipping the top one over, so that the two cards are facing each other. This way, you always see the front of one element, and the back of the other.

We can also apply a very slight Z-translate, to push the element a bit further from the viewer than the card. This addresses an issue where the elements can appear to flicker, because both the card and the backdrop are occupying the same point in 3D space. We push it away from the user so that the backside is actually behind the card itself (which means it'll be in front of the card when it's rotated).

Spacial orientation is a hard thing to visualize (especially with nested rotations!), so don't be discouraged if it's not immediately obvious why this trick works. Playing with the live-editable code should help!

Adding it into our original demo

How do we fit this into our <Foldable> component? We can just add this new backside element to our "bottom half" div, and make sure to use 3D positioning:

Final Details

Here our original demo is again:

A neon alley with a Chinese sign
This is an interactive demo! Try dragging the slider on the right.

There are a couple other small details we haven't covered.

Shading

As the card moves through its first 90 degrees, the bottom half darkens, as if there's a light source that can't light the surface as well as it angles up.

For this effect, I added a new <div>, with a variable opacity. As the card rotation increases, I move closer to opaque.

See this linethis line in the source.

Thickness

As the card moves through the second half, there's the illusion of thickness, as if the card has an edge.

I discovered this one by accident, by playing with the amount of Z-axis translation when adding the backside. To get backface-visibility working, it technically only needs to be 0.01px, but by setting it to 2px, it gives this nice illusion of depth.

See this linethis line in the source.

Translation and Bug-fixing

In this demo, I wanted the whole card to move up as it's unfolded, so that it always appeared centered in the parent container.

This was accomplished with a transform: translateY() on the parent, using the percentage of opening as the value to tween based on.

I've also noticed that sometimes there can be a subtle flickering bug, in the crook of the fold, in certain browsers. The solution was to add a third copy of the image to fill in that small problematic area.

Full details available in the sourcein the source.

Spring physics

In the demo, I'm using React Spring to animate changes in value, when the slider is dragged. Spring physics produce much more organic, beautiful motion than using traditional easing. Its use is outside the scope of this article, but it has excellent documentationexcellent documentation you can consult!

Conclusion

Effects like this can be quite a lot of trouble, but the beauty of React is that it encourages the creation of reusable effects. After following this tutorial, you'll wind up with a <Foldable> component you can easily drop into any future project!

Because this effect is non-trivial, it's also quite rare. This means that it has more of a punch, because it's not something that users are accustomed to!

In this post, we looked exclusively at images, but you may wish to use this effect on other kinds of elements. For example, in a demo I created for a React Europe talkReact Europe talk, I show how a form can be folded up like a letter:

A sample of folding a modal up.

Happily, we can apply many of the tricks we learned here to produce the same effect, but there a couple additional issues we'll have to contend with. I plan to write a second part addressing this concern in the coming weeks!

Join the Newsletter

If you're interested in content like this, you should join my newsletter! Subscribers get sneak peeks at upcoming posts.

I promise it'll be worthwhile and not-too-often. Quality over quantity!