Two inline-block elements, each 50% wide, do not fit side by side in a single row
Having trouble lining up your inline-block
elements side by side? They probably just need a bit of styling TLC. Start by setting up their width with width: 50%
each, but don't forget to take care of the sneaky box model issues. That's where box-sizing: border-box;
comes in. It ensures padding and borders don't push you over that 50%.
Now moving to white-space issues. A bit of font magic does the trick: font-size: 0;
on the parent. Your code would look like this:
Now, we've got a smooth total width of exactly 100%
, meaning both elements cuddle up in one row. Fairytale ending!
Flexbox: your layout fairy godmother
Why not take your elements' relationship to the next level? Enter Flexbox, the toolkit for tighter, cleaner, more flexible layouts, and the superhero to crush whitespace issues:
Here, flex: 1;
whispers to the browser: distribute the space evenly. The result? Perfect side by side fit.
Going for grid: a game changer
Go all out with CSS Grid. It's like flexbox but on steroids. Especially handy for more complex layouts:
This sets up a neat two-column grid, each column taking half of the space. Your elements will thank you.
Parent-child font size tango
Font-size changes affect child elements. After setting font-size: 0;
on the parent, be sure to reset it on the children to save your content from the visibility abyss. It's not you, text, it's your parent's font-size!
Down the troubleshooting rabbit hole
Disobedient elements not lining up? Lookout for these usual suspects:
- Browser defaults: Use Normalize.css or a CSS reset for a uniform starting point.
- Font metrics:
font-size: 0;
minimizes white space, but don't forget to override it for your content. Elements have feelings too! - Zoom and rounding errors: Sub-pixel rendering can act up. It's always a good idea to check across different browsers and zoom levels.
- Content overflow: Keep content within the set width. Use
overflow: hidden;
ortext-overflow: ellipsis;
when things spill over.
Chasing whitespace ghosts
Inline-block
comes with unexpected whitespace. Here's how you can tame it:
- HTML comments: Like how we did in the fast answer.
- Zero space: Use
​
or​
for a non-visible, non-space separator. - Negative margins:
margin-right: -4px;
gives a slight nudge but be watchful for possible overlaps.
Constraints driving creativity
Inline-block puts you in the driver seat for:
- Responsive design: Media queries provide flexibility for different screen sizes.
- Animation and transitions: Bring life to your static elements.
- Vertical alignment:
vertical-align: top;
gets everything in line.
Was this article helpful?