Search code examples
csscss-positionbackground-color

How to achieve this shifted background color of a text-container in CSS (or JS)?


text effect background color shifted

Can someone help me on how to achieve this dynamic shifted color box of a text container in CSS? It should be dynamic to handle long headlines breaking into two lines.

If CSS can't handle this, I am open to JS solutions.

h1 span {
color: black;
background-color: lightblue;
}
<h1><span>HEADLINE<br>LONGER</span></h1>

With a span I can limit the background color to the actual length of the text, but I don't know how to shift it ?

tried this and was closest I can get, but can't wrap my head around the break of text also, as markup won't work in content property:

h1 span:before {  
 content:"'HEADLINE'+'<br/>'+'LONGER'";
  color: #F4BEBE;
  background-color: #F4BEBE;
  top: 40px;
  left: 20px;
  position: absolute;
  z-index: -1;
}
<h1><span>HEADLINE<br>LONGER</span></h1>


Solution

  • You can use a combination of box-decoration-break and linear-gradient()/background-position:

    h1 span {
      -webkit-box-decoration-break: clone;
      box-decoration-break: clone;
      background: linear-gradient(90deg, #f4bebe, #f4bebe);
      background-position: 10px 15px;
      background-repeat: no-repeat;
      padding-inline-end: 10px;
      line-height: 1.5;
    }
    
    
    /* Demo only */
    
    * {
      text-transform: uppercase;
      font-family: system-ui;
    }
    <h1><span>Headline</span></h1>
    
    <h1><span>Hello world</span></h1>
    
    <h1><span>Lorem ipsum dolor sit amet, consectetur adipiscing elit</span></h1>