Css inline-block vs float

I do some tests on float and inline-block , and I noticed that there is a difference between them.

As you can see from THIS EXAMPLE that if I use display:inline-block , the div has a small margin between them, but if I use float:left , it works as expected.

Please note that I am using Eric Meyer Reset CSS v2.0.

This is because I am doing something wrong or this is how the inline-block behaves (in this case it is not very reliable).

HTML

 <!DOCTYPE html> <html> <head> <title>How padding/margin affect floats</title> <link rel="stylesheet" href="css/reset.css"> <link rel="stylesheet" href="css/style.css"> </head> <body> <div id="wrap"> <div class="square"></div> <div class="square"></div> <div class="square"></div> <div class="square"></div> <div class="square"></div> </div> </body> </html> 

CSS (no reset)

 #wrap{ width: 600px; margin:auto; } .square{ width: 200px; height: 200px; background: red; margin-bottom: 10px; /*display: inline-block;*/ float:left; } 
+8
html css css-float
source share
4 answers

Specify the parent element font-size: 0; .

Then set the font-size children to font-size: 12px (or whatever size your design sets), for example:

 #wrap{ font-size:0; } .square{ font-size:12px; } 
+2
source share

I do some tests on float and inline-block, and I noticed there is a difference between them.

No matter which resource gave you that they might not be the same, it is misleading. They are completely different things .

the div has a small margin between them

This is not a margin . This is the space resulting from line breaks between div in HTML. One solution would be to simply remove line breaks, the other would set font-size: 0 to the contained element (thus, no spaces would be displayed).

Please note that if you use the second method, you will need to set another font-size on the inner div s, otherwise the text inside them will not be displayed.

Hope this helps!

+11
source share

This is due to gaps. If you set font-size: 0 in a container element, spaces will disappear (make sure reset font-size on inline blocks).

+7
source share

As I understand it, elements of the built-in block will be displayed with the same automatic interval between fields as for other built-in objects. While elements with a floating point are considered as completely independent in relation to the flow of the document object (so, without annoying spaces).

Sorry, I can’t give a more detailed answer, but this is definitely what I struggled with before. For what it's worth, the spacing should be reliably annoying for the inline elements of the block, you just need to remember to compensate for these pseudo-fields if you try everything that is contained in the parent element without being clicked on the next line.

0
source share

All Articles