I am trying to assign different colors to each line using background-image: repeating-linear-gradient.
div {
--spac: 2em;
line-height: var(--spac);
color: white;
background-image: repeating-linear-gradient(red 0 var(--spac), green var(--spac) calc(var(--spac) * 2));
}
<div>Stack Overflow is a question and answer website for professional and enthusiast programmers. It is the flagship site of the Stack Exchange Network,[4][5][6] created in 2008 by Jeff Atwood and Joel Spolsky.[7][8] It features questions and answers on a
wide range of topics in computer programming.[9][10][11] It was created to be a more open alternative to earlier question and answer websites such as Experts-Exchange. Stack Overflow was sold to Prosus, a Netherlands-based consumer internet conglomerate,
on 2 June 2021 for $1.8 billion.[12]</div>
It works fine, but I just wonder if there are any ways I could make the div area that doesn't have text to become transparent (make the area in the photo circle with black to become transparent).
Another solution I could think of is to split the text based on line break and assign different colors to different lines using for loop, but this is too messy.
I think for background-image: repeating-linear-gradient, there won't be some easy solutions since background-image: repeating-linear-gradient assign the background-color based on the width of the element, not the text. (If there is, please correct me and tell me!)
What will be alternative solutions to solve this?
CodePudding user response:
If you are ready for some hacks, here is one. The trick is to have a white color that covers that area:
.box {
--spac: 2em;
line-height: var(--spac);
color: white;
background-image: repeating-linear-gradient(red 0 var(--spac), green var(--spac) calc(var(--spac) * 2));
overflow:hidden;
}
.box:after {
content:"";
display:inline-block;
vertical-align:top;
clip-path:inset(0 -100vmax -100vmax 0);
box-shadow:0 0 0 100vmax #fff;
}
<div >Stack Overflow is a question and answer website for professional and enthusiast programmers. It is the flagship site of the Stack Exchange Network,[4][5][6] created in 2008 by Jeff Atwood and Joel Spolsky.[7][8] It features questions and answers on a
wide range of topics in computer programming.[9][10][11] It was created to be a more open alternative to earlier question and answer websites such as Experts-Exchange. Stack Overflow was sold to Prosus, a Netherlands-based consumer internet conglomerate,
on 2 June 2021 for $1.8 billion.[12]</div>

