Drawing a line between two <div>
elements is a common layout task in web design. Whether you’re building timelines, connecting cards, or visually linking content blocks, CSS provides several clean and flexible ways to create lines between elements.
In this guide, you’ll learn how to draw horizontal, vertical, and diagonal lines between two divs using only CSS.
🎯 Objective
You have two divs on your page and want to draw a line between them—visually connecting them in a clean and responsive way.
✅ Method 1: Horizontal Line Between Two Side-by-Side Divs
📌 Layout Example:
<div class="container">
<div class="box">Box 1</div>
<div class="line"></div>
<div class="box">Box 2</div>
</div>
🧾 CSS:
.container {
display: flex;
align-items: center;
gap: 20px;
}
.box {
width: 100px;
height: 100px;
background-color: #ddd;
display: flex;
justify-content: center;
align-items: center;
}
.line {
width: 40px;
height: 2px;
background-color: black;
}
✅ Result:
- A clean horizontal line connects the two divs.
- Works great for timelines, cards, and steps.
🔄 Method 2: Vertical Line Between Two Stacked Divs
📌 Layout:
<div class="v-container">
<div class="box">Top</div>
<div class="v-line"></div>
<div class="box">Bottom</div>
</div>
🧾 CSS:
.v-container {
display: flex;
flex-direction: column;
align-items: center;
gap: 20px;
}
.v-line {
width: 2px;
height: 40px;
background-color: black;
}
🎨 Method 3: Diagonal Line Between Two Positioned Divs
To draw a diagonal line, you need to absolutely position the divs and use a pseudo-element or separate <div>
to draw the line.
📌 Layout:
<div class="wrapper">
<div class="dot" id="dot1"></div>
<div class="dot" id="dot2"></div>
<div class="line-diagonal"></div>
</div>
🧾 CSS:
.wrapper {
position: relative;
height: 200px;
}
.dot {
width: 20px;
height: 20px;
background: blue;
border-radius: 50%;
position: absolute;
}
#dot1 {
top: 20px;
left: 50px;
}
#dot2 {
top: 150px;
left: 200px;
}
.line-diagonal {
position: absolute;
top: 20px;
left: 50px;
width: 200px;
height: 2px;
background: red;
transform: rotate(30deg);
transform-origin: left center;
}
🔧 You can dynamically calculate angles and lengths using JavaScript if the layout needs to be flexible.
🧾 Conclusion
Drawing a line between two <div>
elements in CSS is straightforward with layout strategies like flexbox
, absolute positioning
, and creative use of divs or pseudo-elements. Whether you want a horizontal, vertical, or diagonal line, CSS gives you full control—without relying on images or SVG.
Pro Tip: For dynamic interfaces like flowcharts or drag-and-drop UIs, consider using SVG or JavaScript-based connectors (like LeaderLine.js) for precise control.