Explain Codes LogoExplain Codes Logo

How to place div side by side

html
responsive-design
css-grid
flexbox
Alex KataevbyAlex Kataev·Sep 9, 2024
TLDR

Embrace display: flex; on the parent container to systematically align your divs side by side. CSS Flexbox ensures each child div slots horizontally like perfectly fitted puzzle pieces.

<div style="display: flex;"> <div style="flex: 1; background: lightblue;">Div 1</div> <div style="flex: 1; background: lightgreen;">Div 2</div> </div>

Flexbox facilitates equal width for your horizontally aligned divs and provides impressive flexibility for more eclectic layouts.

More methods for side by side placement

Flexbox is groovy, but CSS offers alternative techniques to place divs side by side. Let's explore these methods, tailored to different use-cases:

Floating divs together

This old-school method utilizes the float property. Keep a fixed width on the first div and use clear: both; after the floats to avoid an unexpected catastrophe like misplaced content.

Arranging divs as inline-blocks

If you are no fan of floats or flex, consider this method. display: inline-block lets your divs stand side by side just like text. Handle white-space in your HTML to avoid unexpected gaps smarter than your smart TV.

Crafting div arrangement with CSS grid

CSS Grid allows you to position items in rows and columns, perfect for a sophisticated 2D layout. By setting the column sizes, the divs will arrange themselves side by side like disciplined soldiers.

External stylesheets for a clean slate

An external stylesheet sequesters your styles. It's a boon for maintainability and facilitates encapsulation of CSS. The result is gainful scalability in your codebases.

Building responsive layouts

In the digital realm, responsivity is a responsibility. Ensure that your layout gracefully adapts to different screen sizes by using percentages for widths or media queries.

Monitoring browser compatibility

When using high-functionality CSS features like Flexbox or CSS Grid, cross-check browser compatibility using Caniuse or MDN Web Docs. You don't want to leave any user out!

Overcoming challenges: A quick guide

Seamless inline-blocks tricks

Spaces in display: inline-block can ruin your peaceful layout. Handle it with zero font-size at the parent level or wipe off spaces between elements in HTML code.

Flexing the muscles of different widths

When flex items require distinct widths, play with flex-basis or flex-grow and **flex-shrink properties**. Retain the fixed width by assigning flex-grow: 0`.

Clearfix Hack: a savior after floating

After a float-fest, your layout might act up. Use clearfix hack to ensure the subsequent elements don't wrap around like a rogue tornado.

Floats: watch out for pitfalls

When dealing with floats, elements might slip to the next line if the width is insufficient. Make sure your container width is spacious enough or use min-width to secure your floating elements.