CSS
CSS: How to Place div Elements Side by Side
Displaying <div>
elements side by side is a common requirement when building modern layouts—like columns, product cards, image grids, or navigation bars. With CSS, there are multiple methods to achieve this depending on your layout needs.
In this blog post, you’ll learn:
- ✅ How to place
<div>
s side by side - ✅ Methods using Flexbox, Grid, and Inline-Block
- 🧪 Real examples and use cases
- 💡 Best practices for responsive design
✅ 1. Method 1: Flexbox (Modern and Responsive)
Flexbox is the most popular and flexible way to align elements side by side.
✅ HTML:
<div class="flex-container">
<div class="box">Box 1</div>
<div class="box">Box 2</div>
</div>
✅ CSS:
.flex-container {
display: flex;
gap: 20px; /* optional spacing between divs */
}
.box {
background: #f2f2f2;
padding: 20px;
flex: 1; /* equal width */
text-align: center;
}
✅ This will place the boxes side by side and adjust them responsively.
✅ 2. Method 2: CSS Grid (Powerful for Complex Layouts)
Grid layout offers full control over rows and columns.
✅ HTML:
<div class="grid-container">
<div class="box">Box 1</div>
<div class="box">Box 2</div>
</div>
✅ CSS:
.grid-container {
display: grid;
grid-template-columns: 1fr 1fr; /* Two equal columns */
gap: 20px;
}
.box {
background: #d9f0ff;
padding: 20px;
text-align: center;
}
✅ Use Grid when you need more complex structures or want precise column control.
✅ 3. Method 3: display: inline-block
(Old School)
This method works in older browsers but requires whitespace management.
✅ HTML:
<div class="inline-box">Box 1</div>
<div class="inline-box">Box 2</div>
✅ CSS:
.inline-box {
display: inline-block;
width: 45%;
background: #ffe4b5;
padding: 20px;
margin: 0 2%;
text-align: center;
vertical-align: top;
}
⚠️ Watch out for inline spacing issues due to spaces between elements.
✅ 4. Bonus: Float Method (Rarely Used Now)
Use float: left
only when you have to support older browsers.
.float-box {
float: left;
width: 48%;
margin-right: 4%;
background: #e6ffe6;
padding: 20px;
}
Clear floats after using this method to prevent layout issues:
.clearfix::after {
content: "";
display: table;
clear: both;
}
🧠 Summary
Method | Use Case | Pros |
---|---|---|
Flexbox | Responsive layouts, side-by-side items | Simple, responsive |
Grid | Structured multi-column designs | Powerful, customizable |
Inline-block | Basic side-by-side alignment | Easy, older browser support |
Float (legacy) | Old websites, legacy projects | Still works, not ideal |
🏁 Final Thoughts
Placing <div>
elements side by side in CSS is easy with modern layout systems like Flexbox and Grid. These methods provide clean, scalable, and responsive designs—suitable for everything from simple columns to complex web layouts.
Whenever possible, use Flexbox for row-based layouts and Grid for column-based or multi-row designs. Avoid float
and inline-block
unless you’re maintaining legacy code.