logo
Search검색어를 포함하는 게시물들이 최신순으로 표시됩니다.
    Table of Contents
    [CSS] 마진 병합 현상

    이미지 보기

    [CSS] 마진 병합 현상

    • 21.07.06 작성

    • 22.02.07 수정

    • 읽는 데 3

    TOC

    마진 병합 현상

    • 마진 병합(collapsing margins)이란?
      • 인접한 공간에 margin-bottom과 margin-top 속성을 적용할 경우,
        두 속성 중 큰 속성값이 작은 속성값과 병합하는 현상
      • margin-top과 margin-bottom 속성이 제대로 적용되지 않는 원인!
      • 상하에서만 일어나는 현상으로 margin-left/right 에서는 발생 X
        → Block 요소의 성격을 가지고 있는 태그에서만 발생!

    가. 형제간에 발생하는 마진 병합 현상

    *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에 해당하는 파란색 박스만 아래로 내렸다. 이에 대해서는 이후에 자세히 알아보자.

    profile

    FE Developer 박승훈

    노력하는 자는 즐기는 자를 이길 수 없다