skip to Main Content

I have two spans on adjacent lines, with their background-color set. Unfortunately this leaves a gap between the two lines:

html {
  line-height: 1.5;
}

span {
  background-color: red;
}
<pre>
<span>line 1</span>
<span>line 2</span>
</pre>

Is it possible, by only changing the style used for span, to extend the colored background vertically so that it fills the gap?

One thing I’ve tried using is padding: ... 0;, but it’s not clear what value to use for ... in order to be robust against changes in font-size and/or line-height.

4

Answers


  1. Making line-height: 1; does that job.

    html {
      line-height: 1.15;
    }
    
    span {
      background-color: red;
    }
    <pre>
    <span>line 1</span>
    <span>line 2</span>
    </pre>

    Another way would be of to remove style from html.

    span {
      background-color: red;
      line-height: 1.1;
    }
    <pre>
    <span>line 1</span>
    <span>line 2</span>
    </pre>
    Login or Signup to reply.
  2. I think display: inline-block; will do the trick.

    html {
      line-height: 1.5;
    }
    
    span {
      background-color: red;
      display: inline-block;
    }
    <pre>
    <span>line 1</span>
    <span>line 2</span>
    </pre>
    Login or Signup to reply.
  3. I would just wrap in a flex div to ensure it always works as expected.

    html {
      line-height: 1.5;
    }
    
    span {
      background-color: red;
    }
    
    .col {
      display: flex;
      flex-direction: column;
      align-items: flex-start;
    }
    <pre>
    <div class="col">
      <span>line 1</span>
      <span>line 2</span>
    </div>
    </pre>
    Login or Signup to reply.
  4. You could add a pseudo after element to all but the final span and give that the same background color and if you give it a line height of 1 it will be large enough to cover the gap. Position it just below the span element so any padding is taken care of.

    html {
      line-height: 1.5;
    }
    
    pre>span {
      position: relative;
      background: red;
    }
    
    pre>span:not(:last-child)::after {
      content: '';
      position: absolute;
      left: 0;
      top: 100%;
      width: 100%;
      height: 1lh;
      background-color: red;
    }
    <pre>
    <span>line 1</span>
    <span>line 2</span>
    </pre>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search