Search code examples
htmlcsssvglinedraw

How to draw line on over all element html


I want to draw a line connect two div and I used a svg with position absolute but the button between two div is can't be click.

How could I draw a line with z-index max, position absolute and it can click on element under this line. If you have any idea it will help me a lot, thank you! this is my example

My code :

<html>
<body>
<div style="border: solid; width: 150px;height: 150px;"> div1 </div>
<svg height="210" width="500" style="position: absolute;">
  <line x1="50" y1="0" x2="200" y2="200" style="stroke:rgb(255,0,0);stroke-width:2" />
</svg>
<div style="border: #3F3F3F;width: 150px;height: 150px;display: flex;align-items: center;justify-content: flex-end;">
 <button>button </button>
</div>
<div style="border: solid;width: 150px;height: 150px;top: 360px;position: absolute;left: 169px;"> div3 </div>
</body>
</html>```

Solution

    1. You can add pointer-events:none to the svg element.

    2. It may be better to use a transformed div with height:1px instead of an svg:

    .container {
      position: relative;
    }
    
    .rect {
      width:200px;
      height:200px;
      position:absolute;
      border: solid 1px black;
      box-sizing: border-box;
    }
    
    #rect2 {
      left:350px;
      top: 400px;
    }
    
    .line {
      width: 400px;
      height:1px;
      background:red;
      position:absolute;
      transform:rotate(30deg);
      transform-origin:0 0;
      top:200px;
      left:100px;
    }
    
    button {
      position: absolute;
      top:280px;
      left: 220px;
    }
    <div class="container">
      <button>Click me</button>
      <div class="rect" id="rect1"></div>
      <div class="rect" id="rect2"></div>
      <div class="line"></div>
    </div>