Two inline-block, width 50% elements wrap to the second line
When dealing with display: inline-block
elements with width: 50%
, remove all whitespace using HTML comments or by setting font-size: 0
on the parent and resetting font size on the children. This ensures the elements take up an exact 100% width.
Don't forget to account for margins and padding using box-sizing: border-box;
.
Inline-block elements and whitespace removal
Let's get to the bottom of this. In inline formats, white-space characters introduce extra layout space. When using display: inline-block;
, any white space can interfere with the layout.
- No extra white-space: Eliminate extra white-space between inline-block elements for them to fit side by side.
- Font size zero trick: Set parent's
font-size: 0
to eliminate the white-space. Don't forget to reset the font size on children! - Crafty CSS: Use
white-space: nowrap;
on the parent andwhite-space: normal;
on children to prevent and allow wrapping, respectively.
Utilizing Flexbox: a sleek alternative
If display: inline-block;
is giving you a headache, let me introduce you to flexbox, the superhero of CSS layout models. It handles space distribution like a champ and aligns elements vertically without breaking a sweat.
Flexbox's superpowers do falter against the villainy of older IE versions, so beware and prepare your fallbacks!
Experiments: Not just for mad scientists
Whether you're Frankenstein designing the perfect monster, or simply a developer adjusting margins, use tools like JSFiddle to tweak your code and see immediate results.
Remember, the creature you create might behave differently in different environments (viewports), so ensure your design is responsive.
Test, apply, repeat
Be sure to consider browser compatibility—CSS hacks can cause a disruption across different browsers. Stick with standards-compliant methods, balance it out with responsive design and don't forget accessibility.
Beware the box model components
Margins, paddings, and borders can be sneaky! They can push your elements over the edge (literally!). Be sure to manage these aspects of the box model to avoid wrapping surprises.
Was this article helpful?