Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating a responsive diagonal line in element

Not sure if this is possible, but how would I create a 1px diagonal line that goes from top left of element to bottom right, no matter the width and/or height of that element?

like image 605
mikeriley131 Avatar asked Dec 15 '16 19:12

mikeriley131


2 Answers

You can do this in multiple ways.

1) background image

1.1) SVG

You can create an svg direct as inline code and use it for drawing the line. Using this you can achiev nice effects like shadow, gradient, dotted line, ... and much more. It is also posible to use a svg inside the css background-image element.

jsfiddle

<svg style='width: 100%; height: 100%;'>
    <line x1="0" y1="100%" x2="100%" y2="0"
        style="stroke:rgb(0,0,0);stroke-width:1"/>
</svg>

1.2) fix image (png, jpg, ...)

You can also use a simple image as background image on full div.

jsfiddle

2) create linear background gradient

jsfiddle

.testDiv {
  width: 300px;
  height: 300px;
  background:linear-gradient(to bottom right, transparent calc(50% - 1px),  black calc(50% - 1px), black 50%, transparent 50%);
}

How does this works?

  • you define a gradient from top left to bottom right
  • the color is transparent until 50% - 1 px and again transparent from 50% to end

(read more here)

3) rotated inner div (only on square divs)

jsfiddle

when resizing the testDiv, the line should stay a diagonal.

.testDiv{
  width: 600px;
  height: 600px;
  background-color: gray;
}

.lineDiv {
  position: relative;
  top: 29%;
  left: 29%;
  width: 142%;
  height: 142%;
  border-left: solid thin blue;
  transform: rotate(45deg);
}

How does this works?

  • the outer div has a size (may be dynamic too)
  • the inner div has position relative and width and height are set to 142%
  • top and left are set to 29% (28.7)

-> 142 = sqrt(100^2 + 100^2) (see phytagoras)

like image 186
Jarlik Stepsto Avatar answered Oct 09 '22 20:10

Jarlik Stepsto


background-image from a linear gradient should do :

body {
  background:linear-gradient(to bottom right, transparent calc(50% - 1px), black calc(50% - 1px), black 50%, transparent 50%) yellow;
  /*demo purpose */
  height:50%;
  width:50%;
  margin:auto;
  }

html {
  display:flex;
  height:100vh;
  background:white;
  }
/* end demo purpose */

run snippet full page and resize window's browser to test behavior

like image 38
G-Cyrillus Avatar answered Oct 09 '22 20:10

G-Cyrillus