Align <div>
elements side by side
To quickly align <div>
elements side by side, use CSS Flexbox: simply set display: flex;
on the parent container.
This leverages Flexbox to position child <div>
s horizontally, solving the problem efficiently and responsively.
Techniques for horizontal alignment
Floating elements: a walk down memory lane
float: left;
can be used to align <div>
elements side by side. However, its usage is often discouraged due to the layout issues it can cause.
The clearfix ensures that following elements are correctly displayed, and not affected by our floating div party.
Inline-block: the quiet achiever
For scenarios without flexbox, display: inline-block;
can be a handy tool. Be aware of pesky whitespaces in your HTML.
CSS Grid: for when you're not messing around
CSS Grid excels in two-dimensional layouts, but don't underestimate its use here. It allows for more precise control.
Inline-flex: a hybrid solution
display: inline-flex;
gives you the best of both worlds: inline behavior and flexbox control. Perfect for fitting a flex context into your inline needs.
The devil's in the details
Controlling the box size
Regardless of your alignment method, controlling width is critical:
Debugging and compatibility
Have a conflicting CSS? Use developer tools to resolve. Catering to older browsers? float
might be your friend.
Validation counts
Ensure to use valid HTML/CSS to avoid odd behaviors. Validator tools can help find unintentional errors.
Practical practice
If out-of-the-box thinking is your jam, check the demo links! With Codepen examples, say goodbye to "all theory, no practice."
Was this article helpful?