问题
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.
回答1:
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>
回答2:
The biggest difference is that you dont need to clear inline elements like you do floats.
Float removes an element from the normal DOM flow - allowing content to wrap it. This also means that you need to clear the float on the next object in the markup in order to break out of the float condition.
Inline-block does not require you to clear.
来源:https://stackoverflow.com/questions/42741908/what-is-the-difference-between-display-inline-block-and-float-left