sebko
sebko

Reputation: 545

Why is a float necessary?

Simple one here. I'm aware when creating fluid layouts you need to float your elements, but why? I tried removing the float and some extra space appears in-between elements. Where is this extra space coming from? Why is a float necessary? *{ box-sizing: border-box; }

.box{
  display: inline-block;
  width: 50%;
  border: solid 1px red;
  /*float: left;*/
}

http://codepen.io/anon/pen/WQNvBZ

Upvotes: 0

Views: 74

Answers (1)

Maximillian Laumeister
Maximillian Laumeister

Reputation: 20359

Because inline-block effectively means "treat this element as inline on the outside and block on the inside", the browser treats the newline between the div elements as an actual literal space character, which shows up in between the elements.

By using floats, you change the behavior of this inline flow, and the divs go flush against each other.

Here is an article on how to "fight" this space between inline-block divs, if the space is counter to your design. The TL;DR version is that you can (1) remove the spaces/newlines between the closing and subsequent opening tags, (2) use negative margins, (3) set the font size to zero (so the space doesn't show up), (4) float them instead, like you suggested, or (5) use flexbox.

Upvotes: 1

Related Questions