Css position absolute leaves white space at the top

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-24 11:13:30

问题


I want to absolute position a div but it is not sticked to the top but has a blank space. Container has position:relative and inner block has position:absolute css rules. I tried to play with the code and noticed that changing background-position has some effect and I have no idea why.

<header>
   <div class="header-wrapper">
      <div class="header-slogan-1 text-center">Base info</div>
   <div class="header-info">Info</div>
   </div>
</header>

What I want is to have the green block at the top (see fiddle).

Here is the fiddle

Please can anyone explain the behaviour and answer why the block is shifted from the top?


回答1:


It is shifted from the top, because it is relative to its parent .header-wrapper, that has a top margin. In order to get the desired result, you have to remove position: relative from its parent, therefore it will be relative to the viewport and will be placed at the top.

Edit: I realised, that he margin is actually applied to the child of the wrapper, causing margin collapsing. In order to fix this, you need apply overflow: auto to the parent element. By doing that, you can still have a position: relative on the wrapper, as it is not pushed down by the child. Take a look at the demo:

/* header block */
header {
    height: 536px;
    background-color: #ddd;
    background-position: center;
    background-size: 100% 536px;
    background-repeat: no-repeat;
    overflow: hidden;
}

header .header-wrapper {
    position: relative;
    overflow: auto;
    z-index: 2;
}

.header-slogan-1 {
    font-size: 32px;
    font-weight: 700;
    font-style: italic;
    margin-top: 88px;
}

.header-wrapper .header-info {
    position: absolute;
    top: 0;
    z-index: 3;
    background-color: #4caf50;
    max-width: 600px;
    padding: 25px 25px 25px 75px;
    color: #fff;
}

.text-center {
  text-align: center;
}
<header>
   <div class="header-wrapper">
      <div class="header-slogan-1 text-center">Base info</div>
       
       
   <div class="header-info">Info</div>
   </div>
</header>



回答2:


If I'm understanding this correctly, you want the header to have no space around it. If this is the case, then just add

body {
    margin: 0;
    padding: 0;
}

to the top of your css and you should be all set.




回答3:


I changed margin-top: 88px; into padding-top: 88px; of header-slogan-1 as it does not change my layout. I have an image in wrapper class and it is centered and may exceed the container size, so I need position:relative and overflow:hidden.

Finally I decided to pick my solution. Sorry Adam for not choosing your answer.



来源:https://stackoverflow.com/questions/41895994/css-position-absolute-leaves-white-space-at-the-top

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!