How to preserve whitespace indentation of text enclosed in HTML tags excluding the current indentation level of the tag in the document?

Indenting With Comments

Since browsers ignore comments, you can use them to indent your pre tag contents.

Solution

<html>
  <body>
    <main>
      Here is my code with hack:
      <pre>
<!-- -->def some_function
<!-- -->  return 'Hello, World!'
<!-- -->end
      </pre>
      Here is my code without hack:
      <pre>
        def some_function
          return 'Hello, World!'
        end
      </pre>
    </main>
  <body>
</html>

NOTE: a main wrapper was added to provide enough space for the comments.

Advantages

  • No JavaScript required
  • Can be added statically
  • Minification won’t affect the indentation and reduces file size

Disadvantages

  • Requires a minimum amount of space for the comments
  • Not very elegant unless build tools are used

Removing Indentation With Node

A better solution is to remove the leading white-space using either your build process or back-end rendering process. If you are using node.js, then you can use a stream I wrote called predentation. You can use any language you want to build a similar tool.

Before

<html>
 <body>
   Here is my code:
   <pre>
     def some_function
       return 'Hello, World!'
     end
   </pre>
 </body>
</html>

After

<html>
 <body>
   Here is my code:
   <pre>
def some_function
  return 'Hello, World!'
end
   </pre>
 </body>
</html>

Advantages

  • Seamless way to write pre tags
  • Smaller output file size

Disadvantages

  • Requires a build step in your workflow
  • Does not handle non pre elements with white-space: pre added by CSS

Removing Indentation With JavaScript

See this answer to remove indentation with JavaScript

Advantages

  • Possible to target elements with white-space: pre

Disadvantages

  • JavaScript can be disabled
  • White-space adds to the file size

Leave a Comment