denny
denny

Reputation: 1

create a dashed diagonal line with css linear-gradient

I need a dashed diagonal line inside a div.

in this tread draw diagonal lines in div background with CSS

i found how to make a cross with this code

.crossed {

background: 
   linear-gradient(to top left,
       rgba(0,0,0,0) 0%,
       rgba(0,0,0,0) calc(50% - 0.8px),
       /*rgba(0,0,0,1) 50%,*/
       rgba(0,0,0,0) calc(50% + 0.8px),
       rgba(0,0,0,0) 100%),
   linear-gradient(to top right,
       rgba(0,0,0,0) 0%,
       rgba(0,0,0,0) calc(50% - 0.8px),
       rgba(0,0,0,1) 50%,
       rgba(0,0,0,0) calc(50% + 0.8px),
       rgba(0,0,0,0) 100%);
}

by commenting out the line as shown above it removes 1 of the lines out of the x and leaves me with the diagonal line as needed.

but how can i make the line dashed?

the fiddle is here: fiddle

thanks!

edit: sorry, saw the 100px width in example code, the div is changing width and hight done by js. this changes the diagonal degrees, so transform: rotate(-45deg); wont work

Upvotes: 0

Views: 2660

Answers (1)

Rares Hideg
Rares Hideg

Reputation: 394

A simple option would be for you to use a svg for the dashed background

<div class='box'>
  <svg style='width: 100%; height: 100%;'>
      <line stroke-dasharray="5, 5"  x1="0" y1="100%" x2="100%" y2="0" style="stroke:rgb(255,0,0);stroke-width:2"/>
  </svg>
  <div>
  your content here over the svg
  </div>
</div>

demo here : https://jsfiddle.net/u25q9uq4/1/

if you don't want to you svg in code, you can still use it as a css background with base64,

div.box{
  position: relative;
  width: 211px; 
  height: 55px; 
  border: 1px solid black;
  background: url("data:image/svg+xml;base64,PHN2ZyB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHdpZHRoPSIxMDAlIiBoZWlnaHQ9IjEwMCUiPjxsaW5lIHN0cm9rZS1kYXNoYXJyYXk9IjUsIDUiICB4MT0iMCIgeTE9IjEwMCUiIHgyPSIxMDAlIiB5Mj0iMCIgc3R5bGU9InN0cm9rZTpyZ2IoMjU1LDAsMCk7c3Ryb2tlLXdpZHRoOjIiLz48L3N2Zz4=") no-repeat center center;
background-size: cover;
}  

demo here : https://jsfiddle.net/u25q9uq4/2/

I used this tool to convert the svg to base64

This is the final form of the svg converted

<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100%" height="100%"><line stroke-dasharray="5, 5"  x1="0" y1="100%" x2="100%" y2="0" style="stroke:rgb(255,0,0);stroke-width:2"/></svg>

You can change the color and stroke of the dashed link in this example, convert it, and insert it into your css.

Best of luck.

EDIT: Examples of svg dashed lines

Upvotes: 3

Related Questions