Home >Web Front-end >CSS Tutorial >Why Aren't My Inline-Block Elements Aligning Side by Side?
Consider a scenario where two elements with display: inline-block are assigned 50% width. One might expect them to fit side by side, but instead, they exceed the available space. To resolve this:
Inline-block elements inherit a margin between them, despite appearing to eliminate it visually. This extra whitespace, typically around 4px, causes the total width of the two elements to exceed 100%.
Flexbox or CSS Grid Layout are recommended alternatives to inline-block. They provide better control over spacing and layout without the inherent whitespace issue.
To illustrate the whitespace issue, consider the following code:
body { margin: 0; /* remove default body margin */ } div { display: inline-block; width: 50%; } .left { background-color: aqua; } .right { background-color: gold; }
<div class="left">foo</div> <div class="right">bar</div>
While the elements appear to be adjacent, there is a narrow margin between them in practice.
The above is the detailed content of Why Aren't My Inline-Block Elements Aligning Side by Side?. For more information, please follow other related articles on the PHP Chinese website!