Div elements inside Pre elements add undesirable whitespace above and below line

Advertisements

I have the following html:

pre {}

div.uncovered {
  background-color: red;
}
<!doctype html>
<html>

<head>
  <title>Line numbering test</title>
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <pre>
<div class="uncovered"><code>def f(a, b):</code></div>
<div><code>    return a+b</code></div>
    </pre>
</body>

</html>

I need to have div elements because I would like the background color to span the width of my entire browser window. However, the div element also adds whitespace between the code elements, which I do not want. I tried adjusting the margins and padding of the div element in my CSS to 0, but this had no effect. I also tried playing around with the white-space property of the div, some of the options (like nowrap) would remove the whitespace, but would also remove the spaces before my return statement, which is also not desirable.

I don’t understand why div is adding this whitespace. Div is a block element and following the box model, all whitespace should be accounted for by either the margin or padding. Would someone please explain how this is happening and how I can fix it.

Thanks.

>Solution :

Pre can contain phrasing content i.e. not divs – you need to put the pre inside the divs

You need to reset all the elements (you can limit yourself to pre, code and div if needed

* { margin:0; padding:0;}
div.uncovered {
  background-color: red;
}
<!doctype html>
<html>

<head>
  <title>Line numbering test</title>
  <link rel="stylesheet" href="style.css">
</head>

<body>
<div class="uncovered"><pre><code>def f(a, b):</code></pre></div>
<div><pre><code>    return a+b</code></pre></div>
</body>

</html>

Leave a ReplyCancel reply