22

I have the following HTML:

<h2>Embed Code</h2>
<pre>
  <code>
&lt;script type=&quot;text/javascript&quot;&gt;
  var something = 'else';
&lt;/script&gt;
  </code>
</pre>

And the following CSS:

h2 {
  background:#1e7ca2;
  font-weight: 100;
  font-size: 1.25em;
  padding: 10px 15px;
  margin: 0;
  color: white;
}
pre {
  margin:0;
  padding:0;
}
code {
  margin: 0;
  padding: 0 30px;
  display: block;
  background: #1d1f20;
  color: #839496;
  font-size: .85em;
  line-height: 1.6em;
}

But there's a gap between the h2 and the pre element that I can't seem to get rid of.

You can see the problem in action here: http://jsfiddle.net/gaby/k5V8U/

Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
Shpigford
  • 24,748
  • 58
  • 163
  • 252

4 Answers4

45

What ever is inside <pre> preserves the whitespace as well..

If you remove the whitespace between <pre> and <code> like this

<pre><code>

and

</code></pre>

it gets fixed..

Demo at http://jsfiddle.net/gaby/k5V8U/1/

Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
6

This is due to the fact that <pre> preserves white space. You have empty line breaks at both the beginning and end of your <pre> tag. Change it to the following:

<h2>Embed Code</h2>
<pre><code>
&lt;script type=&quot;text/javascript&quot;&gt;
  var something = 'else';
&lt;/script&gt;
  </code></pre>

You may also need to remove the line breaks at the beginning and end of your <code> tag:

<h2>Embed Code</h2>
<pre><code>&lt;script type=&quot;text/javascript&quot;&gt;
  var something = 'else';
&lt;/script&gt;</code></pre>

Hope that helps!

Ryan Kinal
  • 17,414
  • 6
  • 46
  • 63
2

You've created this gap yourself. The background-color you specified is a property of <code>. By using newlines inside of your <pre> element your actually creating a new line as <pre> preserves white space. You may want to use

<h2>Embed Code</h2>
<pre><code>
&lt;script type=&quot;text/javascript&quot;&gt;
  var something = 'else';
&lt;/script&gt;</code></pre>

If you wish to keep the "margin" but fill it with the color of <code> use

<h2>Embed Code</h2>
<pre><code>
&lt;script type=&quot;text/javascript&quot;&gt;
  var something = 'else';
&lt;/script&gt;
</code></pre>
Zeta
  • 103,620
  • 13
  • 194
  • 236
0

As others have mentioned you need to put <code> element on same line as the content inside it because <pre> consider it start of content. There is also simple JavaScript based solution which I posted in this answer: https://stackoverflow.com/a/23001060/207661 and negative margin based solution which is also in same thread.

Community
  • 1
  • 1
Shital Shah
  • 63,284
  • 17
  • 238
  • 185