Working with <pre>
Recently I've started to work with a lot of text with significant line breaks that I need to manually insert into static HTML files.
Instead of processing them through a script and add the necessary
<br> tags, I've decided it makes for a cleaner and easier editing experience to utilize the
<pre> tag to take advantage of its ability to preserve newlines in the HTML code itself.
Here are some tricks I've found that make this easier.
In order to make your code easier to read, you need to properly indent them.
However, this interferes with
<pre> tag because it will capture those indentation and spaces, which you don't want.
This can be solved by via the CSS property
white-space:pre-line, which only preserving newlines.
<pre> at all?
So, why not use a different element with better semantics than the
<pre> tag if
white-space:pre-line will do the job?
Well, it turns out the
<pre> tag is special.
For a nice editing experience, you would want the following:
...with the opening and closing tags having their own lines.
Why? Because it makes it vastly easier to select them, and without the opening tag "glued" to the first line, it is trivial to indent it to align with the rest of the text.
However, only the
<textarea> tags ignores the newline right after the opening tag. It is introduced as a convenience feature.
<textarea> tag does not ignore the newline right before its closing tag, leaving the usefulness of this "convenience feature" in doubt.
What about the line-break before the end tag? Why does it get ignored?
It gets ignored according to HTML spec:
A line break occurring immediately following a start tag must be ignored, as must a line break occurring immediately before an end tag. This applies to all HTML elements without exceptions. [Ed. including the
This behavior is documented by Wikipedia:
However, the first newline after
<pre>and last newline before
</pre>are ignored, allowing the tags to be placed on their own lines without extra empty lines appearing on the page.
Nest another container without creating newlines
You will need to use another
<pre> tag to do this, in order to ignore the opening newline.
In addition, you will have to set
display:inline-block; width:100% to get rid of the newline after the closing
What if you DO want to preserve spaces and tabs in certain cases, such as ASCII artworks?
You will need to wrap them around another
<pre> tag, and apply
whitespace:pre to switch back to the normal