Arranging elements side by side is a fundamental layout skill in web development. Whether you’re building a product grid, placing images next to text, or aligning cards horizontally, CSS provides several methods to place <div>
elements side by side.
In this post, you’ll learn multiple techniques to align divs horizontally, with examples and best practices.
✅ Method 1: Using float
This is one of the oldest techniques and works well for simple layouts.
📄 HTML
<div class="box left">Left Box</div>
<div class="box right">Right Box</div>
🎨 CSS
.box {
width: 45%;
padding: 20px;
background-color: lightgray;
margin: 2%;
float: left;
}
⚠️ Be sure to clear the float if you’re using this method:
<div style="clear: both;"></div>
✅ Method 2: Using display: inline-block
A cleaner, float-free way to place divs side by side.
📄 HTML
<div class="inline-box">Box 1</div>
<div class="inline-box">Box 2</div>
🎨 CSS
.inline-box {
display: inline-block;
width: 45%;
margin: 2%;
background-color: #dfe6e9;
text-align: center;
padding: 20px;
}
💡 Add
font-size: 0
to the parent container to remove unwanted space between inline-block elements.
✅ Method 3: Using Flexbox (Modern & Preferred)
Flexbox is the most flexible and responsive-friendly method.
📄 HTML
<div class="flex-container">
<div class="flex-box">Box 1</div>
<div class="flex-box">Box 2</div>
</div>
🎨 CSS
.flex-container {
display: flex;
justify-content: space-between;
}
.flex-box {
background: #b2bec3;
padding: 20px;
width: 48%;
text-align: center;
}
🧠 Flexbox automatically handles alignment and spacing, making it great for dynamic layouts.
✅ Method 4: Using CSS Grid
For complex side-by-side layouts with more control, use Grid.
📄 CSS
.grid-container {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 20px;
}
.grid-box {
background: #ffeaa7;
padding: 20px;
}
📄 HTML
<div class="grid-container">
<div class="grid-box">Grid Box 1</div>
<div class="grid-box">Grid Box 2</div>
</div>
🔧 You can add more columns or rows easily by changing the
grid-template-columns
value.
📱 Responsive Tip
Use media queries to stack the divs vertically on smaller screens:
@media (max-width: 600px) {
.flex-container {
flex-direction: column;
}
.flex-box {
width: 100%;
margin-bottom: 10px;
}
}
🧠 Summary Table
Method | Use Case | Responsive? | Modern? |
---|---|---|---|
float | Legacy support, simple layouts | ❌ Manual | ❌ |
inline-block | Lightweight, easy alternative to float | ✅ With help | ✅ |
flex | Recommended for most side-by-side needs | ✅ Built-in | ✅✅✅ |
grid | Complex, multi-row/column layouts | ✅ Built-in | ✅✅✅ |
🎯 Conclusion
CSS offers multiple ways to place <div>
elements side by side, each with its pros and cons. For most modern projects, Flexbox and CSS Grid are the go-to solutions thanks to their simplicity and power. Choose the method that best fits your design and browser support requirements.