Explain Codes LogoExplain Codes Logo

How to place two divs next to each other?

html
responsive-design
css-grid
floats
Nikita BarsukovbyNikita Barsukov·Jan 13, 2025
TLDR

Embrace CSS Flexbox: set display: flex; to the parent container and Voilà, you have your child divs intellectively adjusting themselves side by side.

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

Here, we've crafted a row of two div elements sharing equal width.

A pallet of techniques for solid & flexible layouts

Flexbox might be the troubleshooter of today, however, sometimes a bit of old wisdom could save your day. Let's go on a journey exploring some complementary methods.

Maintain the float but control overflow

For a strong fallback with deep-rooted support:

.container { overflow: hidden; /* Keeping our ducks(floats) in a row */ } .left, .right { float: left; width: 50%; /* Just like sharing a pizza */ }

Ensure the combined width of the floated elements doesn't challenge 100%.

Handling paddings and borders with respect

Box-sizing can be your gentle guardian when dealing with borders and paddings:

div { box-sizing: border-box; /* Paddings & borders are friends, not foes */ }

Vertical alignment with inline-block

For those nostalgic browsers or when you can't get floats to float:

div { display: inline-block; vertical-align: top; }

Tidy up whitespace in your HTML to dismiss any unexpected gaps.

Responsive designs for every screen

Evoke media queries to make your layout fluent across screen sizes:

@media (max-width: 600px) { .left, .right { width: 100%; /* A hug from edge to edge */ } }

Expanding horizons towards advanced layouts

Grid systems for the design enthusiasts

CSS Grid is a painting canvas for complex designs:

.container { display: grid; grid-template-columns: 1fr 1fr; /* Two equal width for two best friends */ }

Pinpointed positioning within relative containers

For the lovers of precision:

.relative-container { position: relative; } .absolute-div { position: absolute; top: 0; left: 0; /* Positioning div at the VIP corner */ }

Unleashing the power of clearfix hack

When floats are in play, maintain sanity with the clearfix hack:

.clearfix::after { content: ""; display: table; clear: both; /* Because peace comes after a clean sweep 😉 */ }

Anticipate problems and keep solutions handy

Remember to keep your layout cross-browser friendly. While flexbox is rather sociable, inline-block and floats can act as trusty backups.

Don't overlook the tricky HTML whitespace that can introduce unwanted spacing in inline-block elements.

In a fluid layout, use percent-based widths to maintain flexibility without being stiff and awkward.

Some friendly debugging tips

  • Sneak peek into developer tools for understanding computed styles.
  • Ensure DOCTYPE is declared for maintaining standard practices.
  • Validate your HTML/CSS for any lurking errors with online validators.