Explain Codes LogoExplain Codes Logo

Align <div> elements side by side

html
responsive-design
css-grid
developer-tools
Alex KataevbyAlex Kataev·Jan 15, 2025
TLDR

To quickly align <div> elements side by side, use CSS Flexbox: simply set display: flex; on the parent container.

<div style="display: flex;"> <div>First</div> <!-- We're number one! --> <div>Second</div> <!-- Always the bridesmaid, never the bride! --> </div>

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.

<div style="float: left;">First</div> <!-- Nothing to see here, just floating around --> <div style="float: left;">Second</div> <!-- I too like to float --> <div style="clear: both;"></div> <!-- Party's over, everyone go home -->

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.

<div style="display: inline-block;">First</div> <!-- Inline and feeling fine --> <div style="display: inline-block;">Second</div> <!-- In line and on time -->

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.

<div style="display: grid; grid-template-columns: auto auto;"> <div>First</div> <!-- Grid to meet you --> <div>Second</div> <!-- It's hip to be square --> </div>

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:

.div-class { width: calc(50% - 10px); /* Subtracting margins, doing the math so you don't have to */ }

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."