Gradient line with dashed pattern

Ela picture Ela · Sep 10, 2015 · Viewed 10.3k times · Source

I need to create a dashed line with a linear gradient. I managed to create a dashed line using <hr /> and the following styling:

line {
  border: 0px;
  border-bottom: 2px dashed;
}

And I also know that to achieve a gradient I need to do:

background: -webkit-gradient(linear, 0 0, 100% 0, from(white), to(black));

Answer

Harry picture Harry · Sep 10, 2015

Based on the code in your own answer, it looks like you need a line which is a gradient in itself (from blue to green) and also have dashed pattern. This is not possible to achieve with one gradient image because spaces cannot be introduced in the middle of a gradient.

However, you can achieve the same effect without using any extra elements (real/pseudo) by using background-image stacking like in the below snippet:

.line {
  margin-top: 50px;
  height: 2px;
  background: linear-gradient(to right, transparent 50%, #223049 50%), linear-gradient(to right, #00b9ff, #59d941);
  background-size: 16px 2px, 100% 2px;
}

body{
  background-color: #223049;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>
<div class="line"></div>

The second gradient in the above snippet is the same as the one in your answer (except the usage of the latest standard cross-browser syntax). The first gradient is the replacement for your hr and it is nothing but a repeating gradient which is transparent for 50% of image's width and the color you need for the other 50%. The background-size of the first gradient image is set as 16px 2px where 16px is the width and 2px is the height. The width of the image determines the width of the dashes. The height (2px) determines the thickness of the line.