C.Marks C.Marks - 7 months ago 34
Javascript Question

CSS Drawing a line between two elements

I've been trying to draw a line down the middle of a series of circles however if I set a line (

.Line1
) to fit between the first and last element then it's drawn from the top left of the first element and not centralised. If i set a line (
.Line2
) to fit in the middle by changing the percentages it will look fine at 100% zoom however if you zoom in or out of the screen it moves around.

I know it is possible to do using pure javascript however I cannot figure out how to do it with css created elements.

<style>
.A,.B,.C,.D, .E {
position: absolute;
width: 45px;
height: 45px;
-webkit-border-radius: 50%;
-moz-border-radius: 50%;
border-radius: 50%;
border: 2px solid black;
background: lightblue;
}
.A {
top: 10%;
left: 50%;
}
.B {
top: 25%;
left: 50%;
}
.C {
top: 40%;
left: 50%;
}
.D {
top: 55%;
left: 50%;
}
.E {
top: 70%;
left: 50%;
}
.Line1{
position: absolute;
left: 50%;
top: 10%;
height: 60%;
width: 4px;
background: black;
}
.Line2{
position: absolute;
left: 51.3%;
top: 15%;
height: 60%;
width: 4px;
background: black;
}
</style>

<body>
<div class = "A"></div>
<div class = "B"></div>
<div class = "C"></div>
<div class = "D"></div>
<div class = "E"></div>
<div class = "Line1"></div>
<div class = "Line2"></div>
</body>


http://codepen.io/anon/pen/ZWMbNe

Answer

You need to take border, width and height into account. you cannot draw half a pixel. For example this is a center line:

.A,.B,.C,.D, .E {
  position: absolute;
  width: 46px;
  height: 46px;
  -webkit-border-radius: 50%;
  -moz-border-radius: 50%;
  border-radius: 50%;
  border: 2px solid black;
  background: lightblue;
}

.Line1{
  position: absolute;
  left: 50%;
  top: 10%;
  height: 60%;
  width: 2px;
  background: black;
  transform: translate(24px,23px);
}
Comments