How to Make HTML Code Blocks Responsive

Alex Hooley headshot

Alex Hooley

21st February 2020 · 1 min read

To make your HTML code tags more responsive and stop them overflowing off the side of the page, wrap them in <pre></pre> tags and apply white-space: pre-wrap; to them like this:

<pre style="white-space: pre-wrap;">
  <code>
    .my-example-code {
      color: deepskyblue;
      margin: 5px 10px;
    }
  </code>
</pre>

White space pre wrap browser compatibility

The white-space:pre-wrap; CSS property is supported by most browsers giving you 95% global compatibility. If you want to spice your HTML Code blocks up a bit try adding the highlight.js library. It automatically detects which language you are using and come with loads of built in styles!

Sources

White-space property - Mozilla MDN Web Docs
Browser compatibility - CanIUse.com
Code Block Styles - highlight.js

Get in touch…

Need help with your website?

I'm a full-stack developer specialising in Next.js, WordPress, & Technical SEO. If you need help with your website then get in touch!

Get Website Help