Here's an HTML showing some code in between two short lines of text
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width" />
<title>Uffa</title>
<style type="text/css" media="screen">
pre {
margin: 0;
}
</style>
</head>
<body>
line before
<pre><code>
some
code
here
</code></pre>
line after
</body>
</html>
When I hover with the mouse via devtools, I see this:
and I don't understand where the vertical spacing before and after the code chunk comes from.
Below is the live snippet, in which, however, only the top space of my example is reproduced.
pre {
margin: 0;
}
line before
<pre><code>
some
code
here
</code></pre>
line after
I have simplified my use case a lot to ask this question. And after the the simplification, I still see the same issue I was concerned about.
However, as somebody suggested to use <pre>
without nesting <code>
into it, I should probably clarify that in the original use case, I'm making use of highlight.js
, which prescribes to write code in between <pre><code >
and </code></pre>
.
CodePudding user response:
Try this code
code {
white-space: break-spaces;
}
line before
<code>
some
code
here
</code> line after
CodePudding user response:
White spaces on the screenshot appear because you have line-breaks after the <code>
and before the </code>
tags.
The
<pre>
HTML element represents preformatted text which is to be presented exactly as written in the HTML file.
Moreover, based on MDN documentation, you should not use HTML markup inside the <pre>
tags.
If you have to display reserved characters such as <, >, &, " within the
<pre>
tag, the characters must be escaped using their respective HTML entity.
So, if you want to show only the text, it is better to use something like this:
p, pre {
margin: 0;
}
<body>
<p>line before</p>
<pre>
some
code
here</pre>
<p>line after</p>
</body>
If you want to show <code>
text as well you have to use HTML entities, and the code will look like this:
p, pre {
margin: 0;
}
<body>
<p>line before</p>
<pre>
<code>
some
code
here
</code></pre>
<p>line after</p>
</body>