Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inline-Block vs. Float - Different widths?

Tags:

css

css-float

HTML

<ul>
  <li><a href="#">Item #1</a></li>
  <li><a href="#">Item #2</a></li>
  <li><a href="#">Item #3</a></li>
  <li><a href="#">Item #4</a></li>
  <li><a href="#">Item #5</a></li>
</ul>

CSS

ul {
  margin: 0;
  padding: 0;
  list-style: none;
}
li {
  display: inline-block;
  width: 20%;
}

My Problem

When I use display: inline-block; my <li> elements are acting as if they were wider than if I use float: left;. I have their width set to 20% (100% / 5) but the last <li> is forced to the next line as if the are too wide... When I use float: left; instead of display: inline-block;, the five <li> elements fit as expected (with the same width)...

jsFiddle: Inline-Block vs. Float

I want to use inline-block due to the fact I don't need to use a clearfix to make the parent <ul> expand to the height of the <li> elements... I may decide to use float if I could find the proper way to use a clearfix in this circumstance... Regardless, I would still like to know why inline-block widths are too wide... These <li> elements should fit five-wide on one line as long as the width is 20% and the content inside is not too wide...

The only question I could find that is similar to mine is this one (which didn't help me): css inline-block vs float

like image 667
derekmx271 Avatar asked Oct 22 '13 23:10

derekmx271


Video Answer


1 Answers

It's simple. If you add a background: red to your li rules you will see that there is a small gap between each li. The gap is not a margin or padding but a whitespace character (a space) which is created when the browser 'collapses' your newlines and tabs. The issue here is your inline elements respect whitespace but floated elements do not.

There are several solutions based on your requirements and how 'hacky' you want to get. You can see them here: Ignore whitespace in HTML

Personally I'd use display:table-cell for my li as it enjoys the best browser support and is the least hacky approach

ul.table {display:table; width:100%}
ul.table > li {display: table-cell; padding: 0; margin:0;}

An equally valid (but less readable) solution would be the remove the whitespace from the source like so:

<ul><li><a href="#">Item #1</a></li><li><a href="#">Item #2</a></li></ul>

This will work in any browser, even IE4. Some people do this with comments to hide the whitespace but I think that's an abuse of comment semantics and still looks ugly in the source anyway.

like image 153
SpliFF Avatar answered Oct 04 '22 17:10

SpliFF