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.
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.
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.
Block-level elements respect both horizontal and vertical margins whereas inline-level elements only respect horizontal margins.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With