Chris Ware
Chris Ware

Reputation: 135

How to create vertical lines spaced out evenly as background using css?

I have been searching for a way to add vertical lines as a background of a div using css but I cannot find this anywhere!

Ideally, I want a div that is 100vh and it has 5 vertical grey lines spaced out evenly as a background. I then want to be able to overlay information - so hoping this can be done through background-image?

Here is something I found but struggling to manipulate it

.lines {
  min-height: 100vh;
  background-image: linear-gradient(90deg, transparent, transparent calc(100% / 3), black calc((100% / 3) + 1px), transparent calc((100% / 3) + 1px)), linear-gradient(90deg, transparent, transparent calc((100% / 3 * 2) - 1px), black calc(100% / 3 * 2), transparent calc(100% / 3 * 2));
  -webkit-transform: translate3d(0, 0, 0);
  transform: translate3d(0, 0, 0);
}
<div class="lines">
</div>

Heres the link to the codepen I got it from.. https://codepen.io/redmile/pen/XgZeOX

Upvotes: 8

Views: 7776

Answers (1)

Temani Afif
Temani Afif

Reputation: 273640

Try like below with 5 backgrounds (each one a line)

html {
  min-height:100%;
  background:
    linear-gradient(blue 0 0) calc(1*100%/6),
    linear-gradient(blue 0 0) calc(2*100%/6),
    linear-gradient(blue 0 0) calc(3*100%/6),
    linear-gradient(blue 0 0) calc(4*100%/6),
    linear-gradient(blue 0 0) calc(5*100%/6);
  background-size:5px 100%; /* Control the width here*/
  background-repeat:no-repeat;
}

Related question to get more details about the calculation: Using percentage values with background-position on a linear-gradient


Another idea with less of code:

html {
  background: linear-gradient(90deg, #0000 calc(100% - 5px), blue 0);
  background-size: calc((100% - 5*5px)/6 + 5px) 100%;
}

Another one:

html {
  background:
    repeating-linear-gradient(90deg,
     #0000 0 calc((100% - 5*5px)/6),
     blue  0 calc((100% - 5*5px)/6 + 5px));
}

And with CSS variables to easily control everything:

html {
  --w:3px; /* Thiclness of the line */
  --n:8;   /* number of lines */
  
  background: linear-gradient(90deg, #0000 calc(100% - var(--w)), blue 0);
  background-size: calc((100% - var(--n)*var(--w))/(var(--n) + 1) + var(--w)) 100%;
}

Upvotes: 17

Related Questions