Reputation: 39484
I have the following code (http://jsfiddle.net/Th5aq/4/):
<p>
Inline code <code>var a = 1;</code> and code block:
<pre><code>
var a = 2;
var b = a + 4;
</code></pre>
</p>
I get two problems:
The code block as a padding on top and bottom. Why?
I would like the code indent to be only the one defined inside the code tag and not all the spaces of the parent tag.
How can I solve these problems?
Upvotes: 1
Views: 2351
Reputation: 19
Looking at Samuel's answer, I found out that while incorrect for the task given, it shows how to actually make it work. Just fill all "indented" whitespace with comments:
<p>
Inline code <code>var a = 1;</code> and code block:
<pre><code>
<!-- -->var a = 2;
<!-- -->var b = a + 4;
</code></pre>
</p>
May be not most elegant answer to this, but with IDE highlightining it's pretty great, and require nothing but pure HTML. And surprisingly, it's finally something working for me without tons of custom JS, which is why I'm digging out so old question.
Upvotes: 0
Reputation: 201818
The elements have no padding, as you can see by inspecting a test page with a browser’s developer tools: the padding
properties have zero values. What you regard as padding is just empty lines at the start and end of the code
element. By the definition of the pre
element, whitespace in it is preserved.
There is a special rule in browsers (being made official in HTML5) that says that a line break immediately after a <pre>
tag and immediately before a </pre>
end tag is ignored. However, this rule does not apply here, due to the <code>
and </code>
tags.
The simplest solution is to remove the newlines:
<p>
Inline code <code>var a = 1;</code> and code block:
<pre><code> var a = 2;
var b = a + 4;</code></pre>
(I have omitted the </p>
tag, since it is invalid and gets ignored by browsers. A p
element cannot contain a pre
element, so the <pre>
tag implicitly closes the open p
element.)
Alternatively, omit the <code>
and </code>
tags. While “logical” in a sense, they do not serve a practical purpose here and, as you have seen, they cause problems in formatting. Except for some specialties like potential effect on machine translation, code
markup just sets default font to monospace, and here pre
already does that.
Upvotes: 2
Reputation: 2258
Because of an indentation:
<p>
Inline code <code>var a = 1;</code> and code block:
<pre><code>var a = 2;
var b = a + 4;
</code></pre>
</p>
Solution:
http://jsfiddle.net/Th5aq/5/
Why? Because of white spaces in HTML
You have between var a
and <code>
white spaces ... can be removed like:
<p>
Inline code <code>var a = 1;</code> and code block:
<pre><code><!--
-->var a = 2;<!--
-->var b = a + 4;<!--
--></code></pre>
</p>
Upvotes: 0