Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unwanted margin in inline-block list items [duplicate]

Tags:

html

css

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:

Unwanted margins

Any idea of what the hell's happening here?

like image 892
Diego Avatar asked Feb 11 '11 12:02

Diego


People also ask

Does margin work on inline elements?

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.

Can inline block have margin?

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.


1 Answers

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 lis 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 :)

like image 73
Kyle Avatar answered Oct 14 '22 21:10

Kyle