Can anyone explain how I can prevent the margin of a sibling div from affecting the other one? It does not logically make sense to me why the browser is laying it out this way.
I am trying to get the yellow box to have it's top/left relative to the parent, but the blue box with a margin-top is affecting the yellow one.
section{ position: relative; } div.options{ position: absolute; left: 10px; top: 10px; display: inline-block; background: #ff0; padding: 50px; } div.content{ height: 100px; width: 100%; background: #09c; margin-top: 50px; }
<article> <section> <div class='options'> </div> <div class='content'> <h1>hello world</h1> </div> </section> </article>
This is known as collapsing margins .
In CSS, the adjoining margins of two or more boxes (which might or might not be siblings) can combine to form a single margin. Margins that combine this way are said to collapse, and the resulting combined margin is called a collapsed margin .
One solution would be to set the overflow
property of the parent element to something other than the default value, visible
.
Values such as auto
or hidden
would produce the expect results.
(See the link above for alternative approaches to work around this.)
section {
position: relative;
overflow: auto;
}
Changing the overflow
property's value establishes a new block formatting context.
9.4.1 Block formatting contexts
Floats, absolutely positioned elements, block containers (such as inline-blocks, table-cells, and table-captions) that are not block boxes, and block boxes with 'overflow' other than 'visible' (except when that value has been propagated to the viewport) establish new block formatting contexts for their contents.
In a block formatting context, boxes are laid out one after the other, vertically, beginning at the top of a containing block. The vertical distance between two sibling boxes is determined by the 'margin' properties. Vertical margins between adjacent block-level boxes in a block formatting context collapse.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.