Explain Codes LogoExplain Codes Logo

Css - Make divs align horizontally

html
responsive-design
css
flexbox
Nikita BarsukovbyNikita Barsukov·Feb 4, 2025
TLDR

To perfectly arrange your divs horizontally, flexbox is your best friend. Put display: flex; into the parent container's CSS, and observe the magic.

.container { display: flex; /* Now we're cooking with gas */ }
<div class="container"> <div>First</div><div>Second</div><div>Third</div> <!-- Div-ide and conquer --> </div>

The parent div becomes a flex container, and all child divs lineup like well-behaved little ducks in a row.

Harnessing Flexbox powers

Guide the flex children

Flexbox is flexible (pun very much intended) and it gives you the power to precisely position your child divs. Use justify-content: space-evenly; for magical horizontal alignment:

.container { display: flex; justify-content: space-evenly; /* Pure sorcery at work */ }

Making it fit all screens

Now, to ensure your layout does not go haywire across different devices, we use media queries to manage div alignment based on viewport size:

@media (max-width: 600px) { .container { flex-direction: column; /* One small CSS rule for you, one giant leap for responsive design */ } }

BEM for the win

Why not make your CSS more familiar and intuitive by using BEM notation:

<div class="container"> <div class="container__item">First</div> <div class="container__item">Second</div> <div class="container__item">Third</div> <!-- Putting the 'B' in BEM --> </div>

Floats: Outdated and Clunky

If you're dreaming of float, wake up! It's the age of flexbox and grid. They're sprightly, responsive, and have an insatiable appetite for order:

.container { display: grid; grid-template-columns: repeat(3, 1fr); /* Behave, or else... */ }

Be Accessible, Be Liked by Google

Here's a secret - Google digs semantic HTML and a webpage that loads faster than the blink of an eye. So keep your images light and your HTML meaningful.

Time for Testing

Remember, diff'rent strokes for diff'rent folks. Test your layout across several browsers and devices. It's the attention to little details like these that separates the novices from the pros.