How to add background to the element that will occupy half of the container (in length)? I can do this with linear-gradient :

 .half-background { border: 1px solid grey; background: linear-gradient(90deg, #69f0ae 50%, transparent 50%); } 
 <div class="half-background">test text</div> 

But this method does not suit me. Is there another way?

  • And why is the gradient option not suitable? - Vadim Ovchinnikov

2 answers 2

Option using pseudo-elements (:before, :after) ,: (:before, :after)

 .half-background{ position: relative; border: 1px solid #ccc; } .half-background:before{ content: ''; position: absolute; top: 0; left: 0; width: 50%; height: 100%; background: #69F0AE; z-index: -1; } 
 <div class="half-background">test text</div> 

    You can make an image the size of 1 pixel of the desired color, put it in the background, set the width to 50%, and also set the color. The color will fill the entire block, and a single-pixel image will occupy only half. In the snippet, a single-pixel black image is set inline via base64.

     .half-background { border: 1px solid grey; background: url(data:image/gif;base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs=); background-size: 50% auto; background-color: cyan; background-repeat: no-repeat; } 
     <div class="half-background">test text</div>