Responsive Markdown Code Blocks hero image
Responsive Markdown Code Blocks
Jan 16, 2023 1 min read
We use Next.JS and react-markdown for rendering markdown content. Rendering code blocks that are responsive can be tricky, mainly due to the way HTML and CSS interact. Learn what we discovered building Serverless DNA.

Using Next.JS and react-markdown to render the static site content for Serverless DNA works great, except where code blocks are concerned using ```. During development and testing, we found that code blocks rendered fine, until we started testing on smaller screens and mobile. On Serverless DNA pages we use bootstrap 5 for CSS and styling and to center code blocks a combination of flexbox and center styles is quite common.

Code blocks are rendered inside a <pre> tag when long lines of code extend beyond the screen width, causing the tag width to be sized so that the code pushes beyond the screen edge. With the large code block expanding this way the parent flexbox container is also re-sized - but not just around the code container but across the entire blog content, which makes the entire blog page render weirdly, see the screen-shot below.

badly rendered web page

There is a definitive CSS answer for why this occurs and it is discussed in more detail in this article. The fix for Serverless DNA was to not use Flexbox for centering blog content and switched to using Bootstrap's grid system via the row class. Doing this removed the problem for our blog article pages altogether, hopefully, this article will help someone trying to work out why their Next.JS code blocks break the rendering of the rest of their markdown content.