Making each HTML line have different background color automatically

This purely CSS solution will make each HTML paragraph line automatically have a new color.

Preview

This paragraph will have each of its lines with a different background color. This is a pure CSS solution with no JavaScript at all!

Html

Click to edit (doesn't update preview)

<p class="background-lines">This paragraph will have each of its lines with a different background color. This is a pure CSS solution with no JavaScript at all!</p>

CSS

Click to edit (doesn't update preview)

.background-lines {
  font-size: 1.25rem;
  color: #fff;
  background: linear-gradient(
    to bottom, 
    #00426f calc(1.25rem * 1 * 1.75),  /* Color 1 */

    #316f00 calc(1.25rem * 1 * 1.75),  /* Color 2 */
    #316f00 calc(1.25rem * 2 * 1.75),  /* Color 2 */

    #0070a5 calc(1.25rem * 2 * 1.75),  /* Color 3 */
    #0070a5 calc(1.25rem * 3 * 1.75),  /* Color 3 */

    #6f001c calc(1.25rem * 3 * 1.75), /* Color 4 */
    #6f001c calc(1.25rem * 4 * 1.75), /* Color 4 */

    #561297 calc(1.25rem * 4 * 1.75) /* Color 5 */
  );
  padding: 0 1.5em;
  line-height: 1.75;
}

Description

What's so special about this?

What makes this CSS solution great is that it scales with the number of lines. Try making the preview box larger by dragging the corner of it, you will see that the gradient doesn't break!

How can gradients have hard edges?

By starting one gradient at the same point as where another gradient stops, the colors don't fade at all and instead appear as different background colors with hard edges.

To make this automatic, I used the calc() CSS function. The formula is font-size * line * line-height. If you edit the line-height, you have to change each gradient stop value to match it.

How do I change the colors?

You can change the colors by editing the HEX values on the linear-gradient. I marked each color with a comment on the CSS.

How do I add more colors?

Adding more background colors to the gradient is fairly straightforward, just continue the gradient the same way I did with the current 5 colors.

How can I give more padding/margin to each line?

To give padding to the left or right side of the text, edit the padding value.

To give more vertical padding to the lines, edit the line-height value. Do note that if you change it, you have to make each color stop match it. In the example you can see that both line-height and each color have the value 1.75 on them – make sure the value is the same between them.