Responsive pre tags in CSS
By Flavio Copes
Learn how to stop preformatted code from overflowing on small screens, using horizontal scrolling or optional line wrapping.
Long lines inside a pre element can make a page wider than the screen.
This often happens with a command that has no natural place to wrap:
cd /some/super/long/super/long/folder
A pre element preserves whitespace by default. For code, the safest fix is usually horizontal scrolling:
pre {
max-width: 100%;
overflow-x: auto;
}
This keeps the code unchanged and lets the reader scroll when a line is too long.
Wrap long lines instead
Sometimes wrapping is better, especially for plain text rather than code:
pre {
max-width: 100%;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
pre-wrap preserves spaces and line breaks while allowing new wraps. overflow-wrap: anywhere lets the browser break a long value when no normal break point exists.
My advice is to use horizontal scrolling for source code. Wrapping can make one code line look like several lines and hide its real structure.
Related posts about css: