skip to Main Content

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>

2

Answers


  1. Hi I think you’re almost there. Here’s an hack I tried out. I know there must be some other solution out there but this is quick and hacky if you don’t mind. I added comments in the code. Take care

    .one {
    margin-bottom: 40px;
    }
    .paragraph {
      position: relative;
      display: inline-block;
      font-size: 32px;
      font-weight: bold;
      text-transform: uppercase;
      line-height: 40px; /*adjust as you wish*/
      margin: 0 0 10px; /* adjust as you want */
    }
    
    .paragraph:before {  
      content:"";
      color: #F4BEBE;
      background-color: #F4BEBE;
      top: 15px; /* adjust as you wish */
      left: 10px; /* adjust as you wish */
      position: absolute;
      z-index: -1;
      width: 100%;
      height: 100%; /* adjust as you wanted */
    }
    <div class="one">
      <span class="paragraph">Headline</span>
      <br/>
      <span class="paragraph">Hero Master league</span>
      <br/>
      <span class="paragraph">Good Morning</span>
    </div>
      
    
    <div>
      <span class="paragraph">Headline on two,</span>
      <br/>  
      <span class="paragraph">lines here</span>
    </div>
    Login or Signup to reply.
  2. 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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search