简体   繁体   中英

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.

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>

After some amount of fiddling around I came to the following solution, where I introduce a linear-gradient on top of the repeating-linear-gradient , giving the illusion that the gradient had stopped. This works by having the first part of this linear-gradient be completely transparent by setting the last value of rgba to 0.0 .

 .gradient { background: linear-gradient(90deg, rgba(255, 255, 255, 0.0) 50%, rgb(255, 255, 255) 50%), repeating-linear-gradient(90deg, green, green 10px, #ffffff 10px, #ffffff 20px); } div { width: 390px; height: 50px; border: 1px solid black; }
 <div class="gradient"></div>

Inspiration for this answer came from this other stackoverflow question and I have modified the code for this specific purpose.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM