I have the following HTML:
<ul> <li> <div>first</div> </li> <li> <div>first</div> </li> <li> <div>first</div> </li> <li> <div>first</div> </li> </ul>
and the following css rules:
ul { padding: 0; border: solid 1px #000; } li { display:inline-block; padding: 10px; width: 114px; border: solid 1px #f00; margin: 0; } li div { background-color: #000; width: 114px; height: 114px; color: #fff; font-size: 18px; }
For some strange reason, the list items appear with a margin around them in both Firefox and Chrome. Looking at firebug, the list items do not have any margin at all, but there seems to be a void space between them.
If I later on add more list items via javascript using
$('<li><div>added via js</div></li>').appendTo($('ul'));
the "margin" doesn't appear around the new elements:
Any idea of what the hell's happening here?
Top and bottom margins do not affect inline elements because inline elements flow with content on the page. You can set left and right margins/padding on an inline element but not top or bottom because it would disrupt the flow of content.
That's the slight misunderstanding part: display: inline; elements can still have margin and padding , and it probably behaves like you expect it to. The tricky part is that: The block-direction margin on inline elements is ignored entirely. The padding on inline elements doesn't affect the height of the line of text.
This is caused by the display: inline-block;
li { display: inline-block; padding: 10px; width: 114px; border: solid 1px #f00; margin: 0; }
Change it to float: left;
.
I thought it was the padding but took a closer look and turns out it was the display :)
Example here.
After further research I have discovered that inline-block
is a whitespace dependent method and renders a 4px margin to the right of each element.
To avoid this you could run all your li
s together in one line, or block the end tags and begin tags together like this:
<ul> <li> <div>first</div> </li><li> <div>first</div> </li><li> <div>first</div> </li><li> <div>first</div> </li> </ul>
Example here.
Hope that helps :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With