Search code examples
csspre

Achieve <pre> result without <pre> tag


Is it possible to achieve this result, where the lines nicely touch each other:

body {
  margin: 0;
  font-family: 'Courier New', monospace;
}

div pre {
  margin: 0;
}
<div class="background_line"><pre>||||||||||||||||||||||||||||||||||</pre></div>
<div class="background_line"><pre>||||||||||||||||||||||||||||||||||</pre></div>
<div class="background_line"><pre>||||||||||||||||||||||||||||||||||</pre></div>
<div class="background_line"><pre>||||||||||||||||||||||||||||||||||</pre></div>

Without adding a <pre> element, so just with css styles. Right now there is to much space when white-space: pre; is added in the css:

body {
  margin: 0;
  font-family: 'Courier New', monospace;
}

div {
  margin: 0;
  white-space: pre;
}
<div class="background_line">||||||||||||||||||||||||||||||||||</div>
<div class="background_line">||||||||||||||||||||||||||||||||||</div>
<div class="background_line">||||||||||||||||||||||||||||||||||</div>
<div class="background_line">||||||||||||||||||||||||||||||||||</div>



<div class="background_line">||||||||||||||||||||||||||||||||||</div><div class="background_line">||||||||||||||||||||||||||||||||||</div><div class="background_line">||||||||||||||||||||||||||||||||||</div><div class="background_line">||||||||||||||||||||||||||||||||||</div>

If it would be possible then it would save me a lot of complexity.


Solution

  • Just removing the 'Courier New' looks like it gets you what you want:

    body {
      margin: 0;
      font-family: monospace;
    }
    
    div {
      margin: 0;
      white-space: pre;
    }
    <div class="background_line">||||||||||||||||||||||||||||||||||</div>
    <div class="background_line">||||||||||||||||||||||||||||||||||</div>
    <div class="background_line">||||||||||||||||||||||||||||||||||</div>
    <div class="background_line">||||||||||||||||||||||||||||||||||</div>
    
    
    
    <div class="background_line">||||||||||||||||||||||||||||||||||</div><div class="background_line">||||||||||||||||||||||||||||||||||</div><div class="background_line">||||||||||||||||||||||||||||||||||</div><div class="background_line">||||||||||||||||||||||||||||||||||</div>

    The original version with the <pre> has the user agent's stylesheet font-family: monospace; taking priority over your font-family: 'Courier New', monospace;.