csslinear-gradientsrepeating-linear-gradient

How to stop a repeating-linear-gradient in CSS?


In order to add a repeating-linear-gradient in CSS one can do this with something like the following code. It will create a nice div-element with horizontal bars.

.gradient {
  background: repeating-linear-gradient(90deg, green, green 10px, #ffffff 10px, #ffffff 20px);
}

div {
  width: 390px;
  height: 50px;
  border: 1px solid black;
}
<div class="gradient"></div>

The challenge however is to have this repeating gradient stop/end half way through the element. The last half of this element should not display the gradient. How can this be achieved?

A possible solution would be to use linear-gradient instead and hard-code all your needed bars. But given the rather large amount of code you would have to write for this solution this is not desirable.

Other searches on the internet did not review how this could be done for this specific use case. With the help of the MDN documentation for example, one can lookup how repeating-linear-gradient works. But since it does not provide an example for this situation, I do not know the best approach for this problem.


Solution

  • Define the gradient size and disable the repetition:

    .gradient {
      background: 
        repeating-linear-gradient(90deg, green 0 10px, #ffffff 0 20px)
        left  / 50%   100% no-repeat;
    /*position / width height */
    }
    
    div {
      width: 390px;
      height: 50px;
      border: 1px solid black;
    }
    <div class="gradient"></div>