How to Make Two Divs Side by Side in CSS: Simple Guide
To make two
div elements side by side in CSS, use display: flex; on their container or set each div to display: inline-block;. Flexbox is the easiest and most modern way to align them horizontally.Syntax
Use a container with display: flex; to arrange child divs side by side. Each child div will then line up horizontally by default.
Alternatively, set each div to display: inline-block; to make them behave like inline elements but keep block properties.
css
/* Using Flexbox container */ .container { display: flex; } /* Using inline-block on divs */ .div1, .div2 { display: inline-block; width: 45%; vertical-align: top; }
Example
This example shows two div elements side by side using Flexbox. They share the container space evenly and have background colors for clarity.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Two Divs Side by Side</title> <style> .container { display: flex; gap: 1rem; } .box { flex: 1; padding: 1rem; background-color: lightblue; border: 1px solid #333; text-align: center; } .box2 { background-color: lightcoral; } </style> </head> <body> <div class="container"> <div class="box">Div 1</div> <div class="box box2">Div 2</div> </div> </body> </html>
Output
Two colored boxes side by side horizontally, each taking about half the width with some space between.
Common Pitfalls
One common mistake is forgetting to set the container's display property, so the divs stack vertically by default.
Another is using float without clearing it, which can cause layout issues.
Also, setting fixed widths without considering container size can cause wrapping or overflow.
css
/* Wrong: divs stack vertically because container is block by default */ .container { /* missing display: flex; */ } /* Right: add flex to container */ .container { display: flex; }
Quick Reference
- Flexbox: Set container
display: flex;for easy horizontal layout. - Inline-block: Use
display: inline-block;on divs and set widths. - Spacing: Use
gapin flex ormarginfor spacing. - Responsive: Flexbox adapts well to different screen sizes.
Key Takeaways
Use
display: flex; on the container to easily place divs side by side.Without setting container display, divs stack vertically by default.
Flexbox provides flexible and responsive horizontal layouts.
Inline-block can work but requires manual width and spacing control.
Avoid floats for layout as they cause more complexity and bugs.