Search code examples
htmlcsstextbackground-color

Background-color on text elements


Can anyone help me out with background-color on some text.

I would like the background color to have about 40-50% of the text's height and to follow up the rest of the text if the text breaks up into another row. Any ideas?

I have tried to play around with the :before and :after selectors, but I unfortunately did not get the result I wanted.

I have also tried to use span within h1 tag, giving it background color and specific height, but nothing aswell. Any ideas on this one?

I want background color to have about 40-50% of the text's height

I want to achieve essentially this:

Example of what i want to achieve


Solution

  • Not sure if i have read your question correctly, however you want a text tag to have a background color you could always put the background on the parent element or use padding on the text tag.

    <h1 style="padding: 2em; background: red;">Sample Text</h1>
    

    Or

    <div style="padding: 2em; background: red;">
     <p>Sample Text</p>
    </div>
    

    Is this what you're trying to achieve?

    Edit: The below is what you're looking for.

    .container {
      width: 50%;
      margin-left: auto;
      margin-right: auto;
    }
    
    .half-highlight {
      font-size: 30px;
      
      background-image: linear-gradient(to right, transparent 50%, green 50%);
      background-origin: 0;
      background-size: 200% 50%;
      background-repeat: repeat-x;
      background-position: 0 100%;
      transition: background-position 0.5s;
    }
    
    .half-highlight {
      background-position: -100% 100%;
    }
    <div class="container">
      <span class="half-highlight">
        Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repudiandae, error tenetur, nihil tempore illum nulla aliquid debitis nostrum sequi harum possimus commodi unde iusto rerum temporibus? Consequatur porro cumque similique.
      </span>
    </div>
    
    <div class="test"></div>