CSS位置绝对值在顶部留有空白 [英] Css position absolute leaves white space at the top

查看:65
本文介绍了CSS位置绝对值在顶部留有空白的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想绝对定位div,但它不粘在顶部,但有空格.容器具有 position:relative ,内部块具有 position:absolute css规则.我尝试使用该代码,但发现更改背景位置会产生一些影响,我也不知道为什么.

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).

这是小提琴

请问谁能解释这种现象并回答为什么方块从顶部移开?

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

推荐答案

它是从顶部移动的,因为它是相对于其父代 .header-wrapper 的,它具有最高的边距.为了获得所需的结果,您必须从其父级中删除 position:relative ,因此它相对于视口并将放置在顶部.

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.

我意识到,他的边距实际上应用于包装器的子级,导致

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>

这篇关于CSS位置绝对值在顶部留有空白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆