使用<pre><code> tag

时间:2018-02-01 18:01:29

标签: html css newline pre blank-line

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.

2 个答案:

答案 0 :(得分:1)

  

这是代码相关标签的行为方式。 代码标记是内联的。

<code>
    var Name = "My Name";
    alert(Name);
</code>

输出:

var Name = "My Name"; alert(Name);
  

pre 标记不显示第一个空行。

<pre>
    var Name = "My Name";
    alert(Name);
</pre>

输出:

    var Name = "My Name";
    alert(Name);
  

标记以及代码标记始终显示第一行

<pre><code>
    var Name = "My Name";
    alert(Name);
</code></pre>

输出:

[A blank line appears here]    
    var Name = "My Name";
    alert(Name);
  

获取空白行的明智方法是使用默认或有用的注释填充第一行。然后你开始编写下一行的代码。 :

<pre><code>// Javascript Code
    var Name = "My Name";
    alert(Name);
</code></pre>

输出:

// Javascript Code
    var Name = "My Name";
    alert(Name);
  

或者

<pre><code>// Javascript to display your name
    var Name = "My Name";
    alert(Name);
</code></pre>

输出:

// Javascript to display your name
    var Name = "My Name";
    alert(Name);

答案 1 :(得分:0)

我认为可行的唯一方法是:

只使用一点JavaScript:

&#13;
&#13;
const code = document.querySelectorAll("pre code");
[...code].forEach(el => el.textContent = el.textContent.replace(/^\n/,''));
&#13;
pre {border: 1px solid #ddd;}
&#13;
<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>
&#13;
&#13;
&#13;

CSS

另一种,只是真的糟糕方式只使用CSS pre:first-line { font-size:0; } - 但这真的很糟糕,因为它迫使你总是把第一行留空(否则,由于font-size: 0

,此类文字不会出现在屏幕上

white-space失败

white-space<pre>标签上使用<code>组合的任何其他方式都无法获得所需的任何内容。