Alvarado87
Alvarado87

Reputation: 115

Different margins in elements with inline-block

I'm switching divs from float:left to inline-block and don't know why some of the divs are displacing, like they have some invisible border or something.

Here are with float:left https://jsfiddle.net/f7op4dze/

div{
    background-color: red;
    width: calc(25% - 40px);
    height: 50px;
    float:left;
    margin:0 20px;
}

And here with inline-block https://jsfiddle.net/dfdxa5hc/

div{
    background-color: red;
    width: calc(25% - 40px);
    height: 50px;
    display:inline-block;
    margin:0 20px;
}

Upvotes: 2

Views: 486

Answers (3)

Cahnory
Cahnory

Reputation: 11

There is (finally) a CSS only solution to this problem

section {
  display: table;
  word-spacing: -2em;
  width: 100%;
}

div {
  display: inline-block;
  word-spacing: normal;
}

Upvotes: 0

Michael Benjamin
Michael Benjamin

Reputation: 372264

As one possible option to fix the problem, set the font-size of the parent to 0.

section { font-size: 0; }

You can restore the font on the child elements:

div { font-size: 16px; }

Demo: https://jsfiddle.net/dfdxa5hc/3/

For an explanation and other possible solutions, see my answer here:

Upvotes: 1

Orun
Orun

Reputation: 4603

There's a space automatically added with inline elements and this space is applied to inline-block as well.

If there's no whitespace (either a space or a return) between the elements in your markup, the inline-block elements will be rendered without a space.

The easiest way to do this and still retain optimal formatting is using comment tags in between the <div> elements like so: https://jsfiddle.net/orvn/wd0ynq98/2/

<section>
     <div></div><!--
  --><div></div><!--
  --><div></div><!--
  --><div></div>
</section>

Upvotes: 2

Related Questions