TL;DR: The margin isn’t a margin—it’s a space. Try using display: block; float: left;
instead.
ALSO: Checkout the amazing list of techniques to combat inline-block space-margins at CSS Tricks
I’ve made a weird discovery about using the inline-block display. I use inline-block elements on my homepage in the Recent Work section.
I noticed that the math for these block elements wasn’t quite adding up—the element width + padding + margin + border should’ve enabled three items on one line; however, the elements were wrapping.
Here’s an example of what I’m talking about:
Even though the margin of each element is set to zero there is seemingly, a margin, between each element.
This problem could be easily solved by removing the display property, floating each gallery item and using a clearfix on the parent:
That solution, however, ignores why that space is being added.
The inline-block display property treats block level elements (e.g. <div>
) as an inline element (e.g. <span>
), and, just like if you had a line break between two <span>
elements, the line-break between the <div>
s is creating a space between the <div>
s. That extra margin is actually a space—not a margin.
Knowing what is creating an inline-block displayed <div>
’s “margin” enables you to create a couple of different solutions.
- First, the dumb and breakable solution, you could remove the spaces and line-breaks in your html
- Second, directly address the space by setting a negative right margin or negative word-spacing for those elements
- Or, Finally, just use
display: block; float: left;
Here’s an example of what the second solution would look like:
It’s a font-dependent solution, isn’t it?
Yezzur, that solution will depend on the font-size of the parent container. An easier solution might be to just set font-size: 0; on the parent container.
The more I play with inline-block, the more I like the comment based solution.
You’ll see more solutions in that CSS Tricks article I have linked up.
Yes Guest, font size 0px is required if you want to display the inline-block elements aligned to center. if u have text in the inner elements u’ll need to set the font size for those back again
Two alternatives:
set font-size: 0 on the immediate parent and redefine the font-size of the affected (inline-block) children
just use float: left. display: block is redundant (as it’s inferred from floating)