Why doesn't top: 0 work on absolutely-positioned elements relative to body?

前端 未结 5 601
难免孤独
难免孤独 2020-12-31 04:36

You can see in the code below that the h1 pushes down the body and the absolutely-positioned block .absolute does not stick to the top. But you als

5条回答
  •  旧时难觅i
    2020-12-31 04:40

    This is caused by h1 having a default margin, which is keeping the body apart from h1 and its sibling .absolute.

    So all you have to do is reset the margin in h1, like you did for body:

    snippet with every margin resetted

    body {
      position: relative;
      margin: 0;
      padding: 0;
      overflow: hidden;
      background-color: silver;
    }
    h1 {
      margin: 0;
     /*if you want to see full text, put this into the flow*/   
      position:relative;
      z-index:1;
    }
    .absolute {
      position: absolute;
      top: 0;
      left: 0;
      width: 50px;
      height: 50px;
      background-color: darkblue;
    }
    .wrapper {
      position: relative;
      overflow: hidden;
      width: 50%;
      height: 200px;
      overflow: hidden;
      background-color: yellow;
    }
    .wrapper > .absolute {
      background-color: darkcyan;
    }

    Some title

    Some title


    snippet with every no margin resetted

    body {
      position: relative;
      /* margin: 0; */
      padding: 0;
      overflow: hidden;
      background-color: silver;
    }
    h1 {
      /* margin: 0; */
      /*if you want to see full text, put this into the flow*/
      position: relative;
      z-index: 1;
    }
    .absolute {
      position: absolute;
      top: 0;
      left: 0;
      width: 50px;
      height: 50px;
      background-color: darkblue;
    }
    .wrapper {
      position: relative;
      overflow: hidden;
      width: 50%;
      height: 200px;
      overflow: hidden;
      background-color: yellow;
    }
    .wrapper > .absolute {
      background-color: darkcyan;
    }

    Some title

    Some title

提交回复
热议问题