Impact of border property on top margin

前端 未结 3 463
失恋的感觉
失恋的感觉 2020-12-20 03:25

Refer to the following code:



        
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-20 04:14

    This is due to margin collapsing (MDN, W3.org).

    In your example the header element contains an unordered list which, by default, has a top and bottom margin. Because of border collapsing, its margin is transferred to the header which in turn is transferred to the body. As a result, the body is pushed down while the header and list aligns with the top of body.

    top: margin of ul, bottom: margin of body

    Adding a border is one method to prevent margin collapsing (see W3 specs). If you want to avoid adding a border, use the other methods such as assign overflow: hidden to the header.

    body {
      height: 500px;
      width: 80%;
      margin-top: 0;
      margin-bottom: 0;
      margin-left: auto;
      margin-right: auto;
      padding: 0;
      background-color: lightgray;
    }
    .header {
      width: 80%;
      height: 100px;
      margin-left: auto;
      margin-right: auto;
      background-color: yellow;
      /*border: solid 1px black;  */
      overflow: hidden;
    }

提交回复
热议问题