Search code examples
htmlcssnewlinepreblank-line

Hide/Remove first newline/blank-line of html code-section using <pre><code> tag


I'm working on a website that has some code and I would like to write:

<pre><code>
line 1
line 2
</code></pre>

But that produces an empty line at the beginning like this as output

[A Blank line in here that I don't want]    
line 1
line 2

I know if I write like this there will be no blank lines but I like to write as shown above.

<pre><code>line 1
line 2
</code></pre>

Please suggest me what can I do, with CSS if possible, to hide or remove the first newline/blank-line so that I can keep the newline in my code without blank-lines appearing at the beginning of all my code sections.


Solution

  • The only way I see it doable is:

    Using just a bit of JavaScript:

    const code = document.querySelectorAll("pre code");
    [...code].forEach(el => el.textContent = el.textContent.replace(/^\n/,''));
    pre {border: 1px solid #ddd;}
    <pre><code>
    1 line
    2 line
    
    4 line
    </code></pre>
    
    <pre><code>1 line
    2 line
    
    4 line
    </code></pre>
    
    <pre><code>
    
    2 line. (Keep intentional newline above)
    
    4 line
    </code></pre>

    CSS

    Another, just really bad way is to use only CSS pre:first-line { font-size:0; } -- but that's really bad since it forces you to always leave the very-first line empty (otherwise such text will not appear on screen due to font-size: 0)

    white-space fail

    Any other way like playing with white-space combinations on the <pre> and <code> tags will not get anything as desired.