Reputation: 43
I have created some simple media objects and stacked them horizontally. I have added 5px of margin, but the space between them looks 10px. Why are the margins not collapsing?
* {
margin: 0;
padding: 0;
}
#container {
margin: 0 auto;
width: 800px;
background-color: blue;
overflow: hidden;
}
aside {
float: left;
background-color: yellow;
width: calc(20% - 10px);
margin: 5px;
padding: 10px;
box-sizing: border-box;
}
main {
float: left;
background-color: greenyellow;
width: calc(80% - 10px);
margin: 5px;
padding: 10px;
box-sizing: border-box;
}
<div id="container">
<aside></aside>
<main></main>
</div>
Upvotes: 4
Views: 2077
Reputation: 21675
Margins only collapse vertically, not horizontally. You have 5px
of margin on all sides of <aside>
and <main>
so there should be 10px
of space.
<aside> left margin + <main> right margin = 10px
Oh, and margins (vertical ones) don't collapse for floated elements.
Upvotes: 0
Reputation: 2777
CSS margin collapsing only occurs vertically & under 3 circumstances:
Adjacent siblings: The margins of adjacent siblings are collapsed (except when the later sibling needs to be cleared past floats). For example:
<p>The bottom margin of this paragraph is collapsed...</p>
<p>...with the top margin of this paragraph.</p>
Parent and first/last child: If there is no border, padding, inline content, block_formatting_context created or clearance to separate the margin-top of a block from the margin-top of its first child block, or no border, padding, inline content, height, min-height, or max-height to separate the margin-bottom of a block from the margin-bottom of its last child, then those margins collapse. The collapsed margin ends up outside the parent.
Empty blocks: If there is no border, padding, inline content, height, or min-height to separate a block's margin-top from its margin-bottom, then its top and bottom margins collapse.
Take a look at Margin Collapsing here in MDN.
In your case they won't collapse, you'd better applying margin to only one side excluding last item in the row:
aside {
float: left;
background-color: yellow;
width: calc(20% - 10px);
margin-right: 5px;
padding: 10px;
box-sizing: border-box;
}
aside.last {
margin-right: 0;
}
Upvotes: 4