Home > Blockchain >  CSS: remove spacing before and after display:block nested in <pre>
CSS: remove spacing before and after display:block nested in <pre>

Time:08-19

I want to display a consecutive series of <pre> elements without any blank space between them (like consecutive lines of a same paragraph).

I can't achieve that while having display: block

Here is a sample code

body {
    max-width: 940px;
    margin: auto;
}

pre {
    display:block;
    white-space: pre-wrap;
    margin-bottom:0;
    margin-top:0;
    padding: 0
}
<p>One-line paragraph.</p>
<pre>One-line pre element, without space before or after.</pre>
<pre>Another pre line.</pre>
<p>Some paragraph.</p>

<!-- EDIT: the actual problematic code : nested pre -->

<pre>
<pre>One-line pre element, without space before or after.</pre>
<pre>Another pre line.</pre>
</pre>

I wish the output would simply have no large interline between each line

NOTE: using display:inline works, but I need to use block because I want the pre lines to be larger than body.

EDIT: I realise this code snippets displays correctly in Stackoverflow, which is not the case of my larger document:

Explanation found (see updated code): pre lines were already nested in pre element. In this case, the CSS solution is to use display: inline-block

CodePudding user response:

You can try to achieve this with the float: left CSS property:

pre:not(.parent) {
  display: block;
  white-space: pre-wrap;
  margin-bottom: 0;
  margin-top: 0;
  padding: 0;
}

.parent pre {
  display: block;
  white-space: pre-wrap;
  margin-bottom: 0;
  margin-top: 0;
  padding: 0;
  float: left; /* new line */
}
<p>One-line paragraph.</p>
<pre>One-line pre element, without space before or after.</pre>
<pre>Another pre line.</pre>
<p>Some paragraph.</p>

<!-- EDIT: the actual problematic code : nested pre -->

<pre >
<pre>One-line pre element, without space before or after.</pre>
<pre>Another pre line.</pre>
</pre>

CodePudding user response:

Just remove the margin of the paragraph tag.

body {
    max-width: 940px;
    margin: auto;
}

pre {
    display: block;
    white-space: pre-wrap;
    margin: 0;
    /* padding: 0; */ /* does nothing */
}

p {
    margin: 0;
}
<p>one-line paragraph</p>
<pre>one-line pre element, without space before or after</pre>
<pre>another pre line</pre>
<p>some paragraph</p>

According to W3, this is the default styling for paragraph elements: margin: 1.12em 0

  • Related