How to make pre-code block 100% responsive in mobile CSS example

In this tutorial, You learn how to make pre-code blocks 100% responsive with CSS.

This tutorial solves the following things.

  • pre tag is not responsive on mobile
  • pre tag should be horizontally scrollable
  • Boostrap pre-code block with horizontal scrollable Pre is an HTML tag used to display code snippets or store the formatted text like line

the pre tag is a full form or abbreviated as preformatted HTML content

pre tag in HTML example

Pre-tag displays the same formatted text in HTML as well as in the browser. A line of text takes the available width of the browser.

  • It preserves the line breaks and blank spaces with formatted text
  • used to display code blocks in programming blogs
  • Benefits site owners to debug code
This is HTML content displayed on the browser using pre tag in HTML
displayed in the second line using pretag

If there is not enough width It overflows the screen with a scrollbar.

By default, it displays with below-applied styles

pre { display: block; font-family: monospace; white-space: pre; margin: 1em 0px;

How to make Pre tag 100% responsive?

100% Responsive means formatted text content should work on mobiles tablets and desktops. Display long line of code blocks should display with a horizontal scrollbar without layout break.

pre tag takes full space, this will be problematic when you are viewing the same on small screens like mobile.

When you are viewing on mobile, the pre-tag should not fail or the line break should still work as expected.

There are multiple ways we can achieve this based on how you want to view pre-tag on mobile.

using white-space

pre { white-space: pre-wrap; }

With this, Line breaks still work words will not break It breaks into multiple lines If there is no available space,

How to disable horizontal scrolling in a pre tag

pre-tag wraps the text by preserving the formatted text.

So if you have a long line of text and display the same in the browser overflows and it adds scrolling by default to make it responsive.

If you want to disable the horizontal scrollbar, use overflow-x with a hidden value

pre {
  overflow-x: hidden;

And user experience is not good if you disable the horizontal scrollbar, So you have to wrap a text in a pre-tag.

Here is a code `how do wrap a text in pre tag in HTML

pre {
  white-space: pre-wrap;
  max-width: 100%;
  height: auto;

Twitter bootstrap pre-block horizontal with scrollbar

By default pre tag with bootstrap CSS display pretext with vertical scrollbar and pre with white spaces

Default It generates the following CSS.

pre {
  font-family: monospace;
  white-space: pre;

To generate horizontally scrollable

 pre {
    pre {
  overflow: auto;
  word-wrap: normal;
  white-space: pre;

In the latest version of bootstrap, we can apply styles to pre and code tags.


You learned pre-tag in an HTML example and make it 100% responsive using normal CSS and bootstrap.