Search code examples
htmlcsspadding

How to have a balanced padding when a line is broken into 2 parts?


In the following snippet, I've noticed that adding left/right padding gives a more balanced color highlighting as desired, see 2. for more details:

.a { 
    font-size: 4em;
    font-family: sans-serif;
    background-color: #ff800f;
}

.b { 
    padding: 0 0.2em;
}

#c { width: 200px; }
1. <span class="a">Hi there</span> not enough space at left/right in comparison to the height of the highlighting
<br>
2. <span class="a b">Hi there</span> better
<br>
3. <div id="c">Hello and <span class="a b">Hi there</span></div>

Question: when a color-highlighted line is broken into two parts, like the Hi / there here in example 3., how to make that there is automatically more padding at the end of the first line, and start of second line?

Here in example 3., it should be like this:

enter image description here


Solution

  • Apply box-decoration-break: clone (requires a vendor prefix such as -webkit- for most browsers except for Firefox) to the span.

    clone:

    "Each box fragment is rendered independently with the specified border, padding, and margin wrapping each fragment..." -(MDN)

    .a {
      font-size: 4em;
      font-family: sans-serif;
      background-color: #ff800f;
      box-decoration-break: clone;
      -webkit-box-decoration-break: clone;
    }
    
    .b {
      padding: 0 0.2em;
    }
    
    #c {
      width: 200px;
    }
    1. <span class="a">Hi there</span> not enough space at left/right in comparison to the height of the highlighting
    <br> 2. <span class="a b">Hi there</span> better
    <br> 3.
    <div id="c">Hello and <span class="a b">Hi there</span></div>

    Further information: https://developer.mozilla.org/en-US/docs/Web/CSS/box-decoration-break