CSS -- Margin Collapsing

Mastering margin collapsing - CSS: Cascading Style Sheets | MDNThe top and bottom margins of blocks are sometimes combined (collapsed) into a single margin whose size is the largest of the individual margins (or just one of them, if they are equal), a behavior known as margin collapsing. Note that the margins of floating and absolutely positioned elements never collapse.https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing

The Rules of Margin Collapsehttps://www.joshwcomeau.com/css/rules-of-margin-collapse/

Definition: Elements' top and bottom margins are sometimes collapsed into a single margin that is equal to the larger of the two margins.

** Margins of floating and absolutely positioned elements never collapse.

Example:

        

  • yomama & yopapa are two boxes stacked vertically (Rule #1) on top of one another (Rule #2)
    • bottom margin for yomama is 20px
    • top margin for yopapa is 10px

        

  • When we inspect yomama, its bottom margin is clearly touching the yopapa box, indicating that the margins are collapsed  

         

  • When we inspect yopapa, its top margin is 10px, which is still 10px away from the yomama

        

  • When the larger margin collapse with a smaller margin, the larger margin wins, in this case, the combined margin has the width of 20px. yomama wins! (Rule #3)
  • Then, we add an extra nesting around yomama -- throw yomama in a <div>!

                

  • Nothing really happens (Rule#4) beacuse instead of applying this margin between yomama and the parent <div>, the margin is directly transfered to the div, i.e. between div and yopapa.
  • However, we can add some padding, or set a height for the parent div to prevent collapsing (Rule #4.1)
    • Set height
      • We set the height of the parent div to 90px to make space for the yomama margin
    • Add padding (extra space between content -- i.e. children -- and border)
      • We added 10px padding (the green bar) at the bottom to prevent the margin being transfered to the div box, instead, we add 10px to the original 20px margin to keep them apart.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值