Why are my div margins overlapping and how can I fix it?

后端 未结 5 835
故里飘歌
故里飘歌 2020-11-27 15:42

I don\'t understand why the margins of these divs are overlapping.

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-27 15:59

    If you can not use padding and really need for margin not to overlap, here is one trick:

    .btn {
        /* hack for a 2px margin */
        border-top: 2px #fff solid;
        /* this is important if you have a background-color
        and don't want to see it underneath the transparent border*/
        background-clip: padding-box;
    }
    

    Please launch this snippet for demo:

    div {
      margin: 10px;
      background: rgb(48, 158, 140);
      padding: 5px 15px;
      font-weight: bold;
      color: #fff;
    }
    
    .fake-margin {
      border-top: 10px solid transparent;
      background-clip: padding-box;
    }
    Margin applied is 10px on each sides
    the first two have only 10px between them
    the last two have 10 + 10px
    = 20 px

提交回复
热议问题