Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Margin collapse on inline-block elements?

Tags:

css

Margins of blocks elements collapse, but not inline-blocks.
Is there a way to force inline-blocks margins to collapse?

.wrapper {      position: relative;      float: left;      width: 100px;      margin: 10px;  }    .wrapper .el {      display: inline-block;      width: 100%;      height: 20px;      background: #000;      margin: 10px 0;  }    .wrapper.block .el { display: block; }
<div class="wrapper">      <div class="el"></div>      <div class="el"></div>      <div class="el"></div>  </div>    <div class="wrapper block">      <div class="el"></div>      <div class="el"></div>      <div class="el"></div>  </div>

Anyone have an idea?
I have already read the documentation on MDN.

like image 434
Simon Arnold Avatar asked Aug 22 '14 21:08

Simon Arnold


People also ask

Does margin work on inline-block?

The block-direction margin on inline elements is ignored entirely. The padding on inline elements doesn't affect the height of the line of text.

What causes margin collapse?

Margin collapse occurs when vertically adjacent margins of block-level elements collide to share a general margin space. The size of this shared space is dictated by the larger number margin. You can visualize this as an arm wrestling match, where the larger margin will take over and win.

Are margins respected in inline level elements?

Block-level elements respect both horizontal and vertical margins whereas inline-level elements only respect horizontal margins.

Do margins on floated elements collapse?

The top and bottom margins of blocks are sometimes combined (collapsed) into a single margin whose size is the largest of the individual margins (or just one of them, if they are equal), a behavior known as margin collapsing. Note that the margins of floating and absolutely positioned elements never collapse.


2 Answers

This is documented in the spec that margins of inline-block elements do not collapse:

8.3.1 Collapsing margins

  • Margins between a floated box and any other box do not collapse (not even between a float and its in-flow children).
  • Margins of elements that establish new block formatting contexts (such as floats and elements with 'overflow' other than 'visible') do not collapse with their in-flow children.
  • Margins of absolutely positioned boxes do not collapse (not even with their in-flow children).
  • Margins of inline-block boxes do not collapse (not even with their in-flow children).
  • ...

Therefore the answer is No. You probably need to alter the margins of the element.

like image 86
Hashem Qolami Avatar answered Oct 11 '22 10:10

Hashem Qolami


The answer is "no" because that's not how inline boxes work so it can't be forced as you asked for. Anything else would be just manipulating the margins of elements which is only a trick or hack.

like image 27
Rob Avatar answered Oct 11 '22 08:10

Rob