- 마진 병합(collapsing margins)이란?
- 인접한 공간에 margin-bottom과 margin-top 속성을 적용할 경우,
두 속성 중 큰 속성값이 작은 속성값과 병합하는 현상 - margin-top과 margin-bottom 속성이 제대로 적용되지 않는 원인!
- 상하에서만 일어나는 현상으로 margin-left/right 에서는 발생 X
→ Block 요소의 성격을 가지고 있는 태그에서만 발생!
- 인접한 공간에 margin-bottom과 margin-top 속성을 적용할 경우,
*html 파일 <!DOCTYPE html> <html lang="ko"> <head> <title>형제간 마진병합</title> <link ref="stylesheet" href="CSS문서명.css" /> </head> <body> <div id="first"></div> <div id="second"></div> </body> </html>
* css 파일 #first { width: 100%; height: 200px; background-color: yellow; margin-bottom: 100px; } #second { width: 100%; height: 200px; background-color: blue; }
위와 같이 #first 안에 margin-bottom: 100px; 를 적용하면 노란색 박스를
기준으로 아래 쪽에 100px 만큼의 공백 발생.
이때 #second 안에 margin-top: 50px; 를 적용해보자.
* css 파일 #first { width: 100%; height: 200px; background-color: yellow; margin-bottom: 100px; } #second { width: 100%; height: 200px; background-color: blue; margin-top: 50px; }
이때 first와 second 사이의 공백의 크기는 100px + 50px = 150px 이 아니라 100px 이다.
이것이 큰 속성값이 작은 속성값을 병합하는 현상!
- margin-top 속성이 부모에게 영향을 미치는 것
*html 파일 <!DOCTYPE html> <html lang="ko"> <head> <title>부모자식간 마진병합</title> <link ref="stylesheet" href="CSS문서명.css" /> </head> <body> <div id="parent"> <div id="child"></div> </div> </body> </html>
* css 파일 #parent { width: 100%; height: 500px; background-color: yellow; } #child { width: 300px; height: 300px; background-color: blue; margin-top: 100px; }
위의 경우 child 에만 margin-top: 100px; 를 적용하였기 때문에, parent는 가만히 있고 child만 100px의 상부 공백을 둘 것이라고 생각할 수 있다. 하지만 이 경우 child는 parent에 속해있기 때문에 parent 까지도 상부에 100px의 공백을 두게 된다.
어떻게 해결할 수 있을까?
position 속성을 이용하여 해결한다!
* css 파일 #parent { width: 100%; height: 500px; background-color: yellow; } #child { position: absolute; width: 300px; height: 300px; background-color: blue; margin-top: 100px; }
position: absolute; 라는 속성을 child에 적용하여 child에 해당하는
파란색 박스만 아래로 내렸다. 이에 대해서는 이후에 자세히 알아보자.
