How to Make Pre Tags 100% Responsive in CSS

Learn how to quickly make your HTML pre tags 100% responsive by adding a couple of CSS properties.

A problem that I often see on other tutorial websites is that long code snippets (which are wrapped by pre tags) overflow the width of the page, and cause their page layout to break.

This happens because by default pre tags have the CSS white-space property set to normal, like this:

pre {
  white-space: normal;
}

To fix the issue you simple change normal to pre-wrap:

pre {
  white-space: pre-wrap;
}

This is a great improvement, but this doesn’t solve the overflow issue completely, because pre-wrap only addresses whole lines of code (a collection of code terms on a line, separated by white space).

What happens if individual words in your code lines are so long that they go beyond the width of your page?

Then your layout still breaks, because pre-wrap doesn’t address individual words.

A good example is a directory path, which can easily get beyond 50 characters in length, which is too wide for many layouts, especially on mobile. Here’s an example from my own computer:

cd /Users/david/Dev/techstacker/content/posts/how-to-make-seo-friendly-urls/how-to-make-seo-friendly-urls.md

Because there’s no white space between words in the line above, it’s read as one long word by your browser. If it had been separated by spaces between each word, it would wrap just fine because of the pre-wrap property we just discussed. But it’s read as one long word.

To fix this issue, we add another CSS property to the pre tag, called word-break, and give it a value of break-all. Like this:

pre {
  white-space: pre-wrap;
  word-break: break-all;
}

Now your pre tags are 100% responsive.


Has this been helpful to you?

You can support my work by sharing this article with others, or perhaps buy me a cup of coffee 😊

Kofi

Share & Discuss on