Explain Codes LogoExplain Codes Logo

How to prevent inline-block divs from wrapping?

html
responsive-design
css
layout
Nikita BarsukovbyNikita Barsukov·Oct 26, 2024
TLDR

Want to keep your inline-block divs nicely in line? Use white-space: nowrap; on their container and display: inline-block; on each div:

.container { white-space: nowrap; } // Buttering the container for a smooth slide .div { display: inline-block; } // Divs set to 'synchronized swim' mode

This makes .container the head honcho, preventing its .div elements from dropping to a new line.

Overflow showdown

To keep things tidy, employ overflow when using white-space: nowrap;. If content exceeds the container's bounds:

.container { white-space: nowrap; overflow: hidden; } // 'What's in the box' trick

Setting overflow: hidden; ensures excess content stays under wraps, curbing any layout spillage. But if you want scrolling, set overflow: auto;. It's like automatic doors for your divs.

Exploring the alternatives: Flexbox and Float

Although white-space: nowrap; is handy, we also have tools like flexbox and float:

.flex-container { display: flex; flex-wrap: nowrap; } // Flexbox: yoga master of layouts .float-div { float: left; } .clearfix::after { content: ""; clear: both; display: table; } // Float: layout's backstroke swimmer

These alternatives provide additional power and flexibility to control layouts.

Responsive design with the right width

Using white-space: nowrap; doesn't necessarily mean you have to set a fixed width for your inline-block divs. They can take up as much horizontal space as available, maintaining a flow that feels more responsive and natural.

Overflow and viewport harmony

Preventing wrapping might create a wider content area than the viewport width. If horizontal scrolling makes you queasy, use overflow: auto; on your .container to give scrollbars when needed.