Tag <pre> Not Responsive in Mobile Screens with Tailwind CSS
The <pre> tag in Tailwind CSS is not responsive on mobile screens, causing broken and disruptive layouts.

- Fauzan My
- 2 min read

It’s quite frustrating that the <pre></pre>
tag in Tailwind CSS is not responsive on mobile screens. The content layout will expand horizontally, causing the design to break or become unresponsive.
The arrangement of the <pre>
tag will stretch and ruin responsiveness, as shown in the following code structure:
<main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 grid gap-6 md:grid-cols-3">
<article class="md:col-span-2 prose mx-auto">
<h1>Lorem ipsum dolor sit amet</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed pharetra sapien nunc, dictum semper quam mollis id.</p>
<pre>
<code>
<!--Your code... -->
</code >
</pre>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed pharetra sapien nunc, dictum semper quam mollis id.</p>
</article>
<aside class="p-4">
<p>Lorem Ipsum...</p>
</aside>
</main>
The rendering result will overflow on mobile screens, appearing as the screenshot below:

Is this a bug in Tailwind CSS 3.2.7?
After some tweaking and searching for solutions on Google, it turns out that the same issue has been experienced by many other software engineers, as seen in this GitHub issue: https://github.com/tailwindlabs/tailwindcss-typography/issues/96.
Where the problem lies:
When the <pre>
content is wrapped within a flex and grid parent, it experiences stretching.
The solution:
The issue with the <pre>
tag is not solely a “bug” within Tailwind CSS itself. Since the <pre>
tag contains source code, including spaces and line breaks, it can cause text to expand on narrower mobile screens.
To address this problem, you need to take several actions:
- Use a Responsive Container: Wrap the
<pre>
tag in a responsive container element, such as ```, to allow users to scroll the content horizontally if necessary.
<div class="overflow-x-auto">
<pre>
<!-- Your content -->
</pre>
</div>
-
Use Custom CSS Classes: Create custom CSS to handle this issue by adding CSS properties like white-space: pre-wrap; or word-wrap: break-word; to control the text behavior within the
<pre>
tag. -
Use Media Queries: If the layout still stretches on mobile screens, use CSS media queries to alter the behavior or style of the
<pre>
tag on smaller screens.
These are the solutions for addressing the non-responsive <pre>
tag issue on mobile screens.