Pure CSS "Read More" toggle

Recently I set out to create a description/synopsis area that truncated text and displayed a "Read More" toggle if the text was too long. Almost the only limitation I set was that I wanted it to be done without Javascript.

I naïvely thought this would be easy using some overflow properties but I soon realised that that idea wouldn't work as text-overflow: ellipsis only works if the text is on a single line. After this I found some clever solutions yet none of them quite fit my use case.

After much pondering I realised several things:

  • It's much easier to hide one div and show another than to truncate/untruncate text using CSS.
  • The important part of a paragraph may not be within the first X characters.
  • Even when truncating at the end of whole words, truncating can end in weird results.

This led me to decide that for UX's sake there should be a separate shorter version of the text that encapsulates the important points of the full piece of text. After making this decision I quickly found a tidy way to choose which version of the text to display in the form of the checkbox hack. This hack allows you to control which of two elements are shown by ticking/unticking a hidden checkbox through it's label.

While this achieved the desired outcome, it didn't look very pretty. Again naïvely I thought that I would be able to whack some animations on the containing element and all would be well.

The first problem is that the two elements containing text were different sizes. As one faded out and the other faded in, the surrounding div looked awful. This problem was overcome by putting a delayed transition on the max-height (auto heights cannot be transitioned, so instead transition between a 0 and massive max-height). You can see an example of the resulting code below.

See the Pen Good Transition by Michael Gwynne (@votemike) on CodePen.

If you think you have a better way of achieving such a result, feel free to fork the Pen and drop me an email.