Search code examples
htmlcode-snippetspre

Why the code in a pre tag which is inside a table cell look terrible?


I have tried to use html to make my own quick reference to different programming language, in the reference I tried to put the code snippet inside a pre tag which is inside a cell tag.

First, html like this, and the codes look terrible

                <td>
                    <pre><code>if (..){

                    } else {

                    }</code></pre>
                </td>

Then, i have fixed the problem by removing all the indent in pre tag

                    <td>
<pre><code>if (..) {

} else {

}</code></pre>
                    </td>

This picture shows the difference, the first cell is written the beautiful indent html, while the others cell are written by ugly indent html. I don't understand the reason, and if there any ways to fix the problem ? example


Solution

  • The pre element preserves whitespace (including spaces and line breaks) exactly as written in the HTML source. This completely explains what happens. In your first code snippet, e.g. the third line has a large number of spaces before the text } else {, and those spaces will be preserved. The first line in that pre element has no leading spaces, since the line starts after the start tag <pre>.