Search code examples
htmlcssgradient

how can I create a dashed line with two color grey and light grey


I want to create a dashed line like the image below using only CSS and HTML with minimal code. The distribution percent of dashes between two color may vary depending on another CSS variable, so I should be able to set a (percent of grey) and (100%—(percent of grey)) for light grey. I also want to be able to set the width and height of dashes and the width of gaps between them.

dashed line with two color

And no matter how much I try repeat(), grid, etc, I can not achieve this.

I also read these two but could not make changes to fit my needs: How to create a dashed border with two alternating colours? Gradient line with dashed pattern

Can you guys please help me to solve this challenge?

I tried using background-image,background-size,background-position, and background-repeat attributes with a combination of linear-gradient() and repeating-linear-gradient() functions, but I could not succeed in using them in any combination with different values.

I expect this dashed image with two colors


Solution

  • One idea is to use two linear gradient, one rendering the dashline, one splitting the 70% lighten percentage, and overlay them with the lighten blend-mode. All these can be extracted as a custom-property to control easily.

    .dashed-line {
      width: 100%;
      height: 6px;
    
      --lighten-percentage: 70%;
      --dash-width: 18px;
      background-image: repeating-linear-gradient(to right, #ffff 0% 40%, #454f5b 40% 100%), linear-gradient(to right, #0000 0% round(down, var(--lighten-percentage), var(--dash-width)), #bbb round(down, var(--lighten-percentage), var(--dash-width)) 100%);
      background-size: var(--dash-width) 100%, 100% 100%;
      background-blend-mode: lighten;
    }
    <div class="dashed-line"></div>