So, I normally format my HTML source code like so:
<article>
<section>
<p>
Text...
Text...
</p>
<pre>
Code...
Code...
Code...
</pre>
<p>
Text...
Text...
</p>
</section>
</article>
However, this formatting style is not compatible with PRE elements since all white-space inside those elements is significant.
See here: http://jsfiddle.net/pjEYm/
In order to fix the presentation of the code block, I would have to format the source code like so:
<article>
<section>
<p>
Text...
Text...
</p>
<pre>
Code...
Code...
Code...</pre>
<p>
Text...
Text...
</p>
</section>
</article>
See here: http://jsfiddle.net/pjEYm/1/
This, however, reduces the tidiness and readability of my source code.
I would like to use a solution which would enable me to preserve my formatting style.
I tried setting the white-space
property. The closest to a solution is white-space: pre-line
, but it also removes all indentation from the code.
See here: http://jsfiddle.net/pjEYm/2/show/
So, I went with JavaScript:
$( 'pre' ).each( function () {
var lines, offset;
// split the content of the PRE element into an array of lines
lines = $( this ).text().split( '\n' );
// the last line is expected to be an empty line - remove it
if ( lines.length > 1 && lines[ lines.length - 1 ].trim() === '' ) {
lines.pop();
}
// how much white-space do we need to remove form each line?
offset = lines[ 0 ].match( /^\s*/ )[ 0 ].length;
// remove the exess white-space from the beginning of each line
lines = lines.map( function ( line ) {
return line.slice( offset );
});
// set this new content to the PRE element
$( this ).text( lines.join( '\n' ) );
});
Live demo: http://jsfiddle.net/pjEYm/3/
While this works, I would still prefer some sort of CSS solution. Is there one?
There is no CSS solution, except in the sense that you could set a negative margin on the
pre
element, but then you would need to set it using a fixed number and thech
unit (which is not universally supported). This would be rather clumsy and inflexible and unreliable.The
pre
element means preformatted text, and you should not use it unless you really want that. For program code, you could use just forced line breaks (<br>
) and leading no-break spaces for indentation (theoretically, not reliable, but works in practice). It is however simplest and safest to include just the data you want to show as preformatted, even if it breaks the layout of the HTML source (which is of interest only to the few people who read it).