Skip to main content

CSS Floating Text

Stylised 3D text.

I saw this post about styling text using CSS’s paint-order property and decided to experiment.

The end result went in a slightly different direction, but I think it turned out nicely. Try hovering over each letter:

See the Pen Text Layers by m-allanson (@m-allanson) on CodePen.

Letter Layers

Some trickery is needed make each letter hover individually. Looking at the letter B, there’s three layers:

<span class="letter">
  B
  <span class="letter-top" inert>B</span>
  <span class="letter-shadow" inert>B</span>
</span>
  • letter sits in the flow of its parent element, but is invisible. This is used for positioning the remaining layers.
  • letter-top is the top-most visible letter. Transforms “up” on mouse hover.
  • letter-shadow is the shadow. Shrinks slightly on hover for a shadowy feeling.

Transitions

Transitions are triggered by hovering .letter, with separate transitions on .letter-top and .letter-shadow for a 3D effect.

:root {
  --on-enter: transform 0.2s ease-in-out;
  --on-exit: transform 0.7s ease-in-out 0.1s;
}

.letter {
  & .letter-top {
    transition: var(--on-exit);
  }

  &:hover .letter-top {
    transform: translateX(-0.1ch) translateY(-0.1ch);
    transition: var(--on-enter);
  }

  & .letter-shadow {
    transform: translateX(0.1ch) translateY(0.1ch);
    transition: var(--on-exit);
  }

  &:hover .letter-shadow {
    transform: translateX(0.1ch) translateY(0.1ch) scale(0.9);
    transition: var(--on-enter);
  }
}

Units

The text is sized as a proportion of viewport width vw and the transitions as a proportion of character height ch. This makes the whole thing scale nicely based on the browser width.