/

How to Create Responsive Pre Tags in CSS

How to Create Responsive Pre Tags in CSS

I encountered an issue with responsiveness in some of my blog posts, which turned out to be related to code snippets. Specifically, the code snippets in these posts were extending beyond the normal page width without any line breaks.

To address this problem, I discovered that the code snippets on my blog are automatically inserted within a code tag, which is then nested inside a pre tag. The default CSS white-space property for the pre tag is set to normal, but to fix the responsiveness issue, we need to change it to pre-wrap:

1
2
3
pre {
white-space: pre-wrap;
}

By setting the white-space property to pre-wrap, the code snippets will now wrap to the next line when they reach the edge of the container.

However, there may still be instances where long words within the code snippets can disrupt the layout. To prevent this issue, you can also include the following CSS rule:

1
2
3
pre {
word-break: break-all;
}

With this rule, long words will break at any character if they exceed the available space, ensuring that the layout remains intact.

By making these adjustments to the CSS for pre tags, you can create responsive code snippets that adapt to the width of the container and handle long words appropriately.

Tags: responsive design, CSS, code snippets, pre tags