개발 공부/CSS
Margin Collapse , Block formatting context
차정
2022. 8. 31. 21:53
See the Pen overflow : hidden by JEONG (@cona) on CodePen.
부모요소와 자식요소의 border 가 겹쳤을때 자식요소의 margin이 작동하지 않는다. -margin collapse
이 때 margin collapse를 피하는 방법은 여러가지가 있다.
대표적으로 부모요소에 padding : 1px; 을 주거나 border: 1px solid black; 을 주는것이다.
그외에도 새로운 블록서식컨텍스트를 생성하는 방법이 있다.
BFC가 생기는 조건
- html root 태그 (body 태그는 만들어지지 않는다)
- none을 제외한 float
- position: fixed, absolute
- display: inline-block, table, table-cell, table-caption
- overflow: visible을 제외한 모든 값
- display: flow-root (일부 브라우저만 동작함)
- display: flex, inline-flex, grid, inline-grid
새로운 블록서식컨텍스트가 생기면, margin collapse가 만들어지지 않는다.
https://www.w3.org/TR/CSS2/box.html#collapsing-margins
Note the above rules imply that:
- 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).
- The bottom margin of an in-flow block-level element always collapses with the top margin of its next in-flow block-level sibling, unless that sibling has clearance.
- The top margin of an in-flow block element collapses with its first in-flow block-level child's top margin if the element has no top border, no top padding, and the child has no clearance.
- The bottom margin of an in-flow block box with a 'height' of 'auto' and a 'min-height' of zero collapses with its last in-flow block-level child's bottom margin if the box has no bottom padding and no bottom border and the child's bottom margin does not collapse with a top margin that has clearance.
- A box's own margins collapse if the 'min-height' property is zero, and it has neither top or bottom borders nor top or bottom padding, and it has a 'height' of either 0 or 'auto', and it does not contain a line box, and all of its in-flow children's margins (if any) collapse.