Emily Chewy Emily Chewy - 9 months ago 35
CSS Question

What is the difference between display: inline-block and float: left

****** Despite being marked as a duplicate - the other question does not answer my question ******

I'm want to know why not just use display:inline-block all of the time INSTEAD of float:left. Inline-block seems to be much easier to control in terms of layout and not having issues with having to clear floats etc. I'm trying to get my head around why use one instead of the other.

Many thanks,

Emily.

Answer Source

The purpose of float is to allow text to wrap around it. So it's moved to the left or right side and taken out of the page flow. Line boxes containing the other text then avoid overlapping with the floated element. It forms a block-level, block container. It is not vertically aligned with any other content.

body {
  width:300px; 
}
.float-example span {
  float:left;
  width: 100px;
  border:2px dashed red;
}
<section class="float-example">Lorem ipsum dolor sit amet, consectetur 
adipiscing elit, <span>I like to use float!</span> sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</section>

The purpose on inline-block is to be a block container that sits inside a line box. It forms an inline-level, block container within the normal flow of the content. It's vertically aligned with the other content of the line box it is in.

body {
  width:300px; 
}

.inline-block-example span {
  display:inline-block;
  width: 100px;
  border:2px dashed red;
}
<section class="inline-block-example">Lorem ipsum dolor sit amet, consectetur
adipiscing elit, <span>I like to use inline-block!</span> sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
</section>