【问题标题】:Css position absolute leaves white space at the topCSS位置绝对在顶部留下空白
【发布时间】:2017-06-13 06:06:17
【问题描述】:

我想绝对定位一个 div,但它没有粘在顶部,而是有一个空格。容器有position:relative,内部块有position:absolute css 规则。我尝试使用代码并注意到更改背景位置有一些效果,但我不知道为什么。

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

我想要的是在顶部有绿色块(见小提琴)。

这里是fiddle

请任何人解释该行为并回答为什么该块从顶部移动?

【问题讨论】:

  • 好的,谢谢您的回答。我想将.header-slogan-1 元素的margin-top 更改为padding-top 就可以了。但是position:relative 的行为对我来说仍然很棘手。
  • 如果解决了您的问题,请接受答案
  • 我并不完全清楚为什么坐标原点从顶部边框下方 88px 开始,而背景从顶部开始着色。从我的角度来看,它应该是对应的。如果包装器移动,则应相应地对其进行阴影处理。如果没有,它应该从顶部 0px 开始,并且不应该有边距。这有点棘手。不过没关系,我可以关闭问题了。
  • "从我的角度来看应该是一致的。"但显然这不是 css 的工作方式

标签: css css-position


【解决方案1】:

我将margin-top: 88px; 更改为padding-top: 88px;header-slogan-1,因为它不会改变我的布局。我在包装类中有一个图像,它居中并且可能超过容器大小,所以我需要position:relativeoverflow:hidden

最后我决定选择我的解决方案。抱歉亚当没有选择你的答案。

【讨论】:

    【解决方案2】:

    如果我的理解正确,您希望标题周围没有空格。如果是这种情况,那么只需添加

    body {
        margin: 0;
        padding: 0;
    }
    

    到你的CSS顶部,你应该已经准备好了。

    【讨论】:

      【解决方案3】:

      它从顶部移动,因为它相对于它的父 .header-wrapper,它有一个上边距。为了得到想要的结果,你必须从它的父级中移除position: relative,因此它将相对于视口并被放置在顶部。

      编辑:我意识到,他的边距实际上应用于包装器的孩子,导致margin collapsing。为了解决这个问题,您需要将overflow: auto 应用于父元素。通过这样做,您仍然可以在包装上使用position: relative,因为它不会被孩子推下。看看演示:

      /* 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>

      【讨论】:

      • 但是包装器没有边距?我没看到。 .header-slogan-1 具有 margin-top 属性,但它不是包装器。
      • 你是对的,你可以用overflow: auto来解决这个问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-11
      • 2023-02-05
      • 1970-01-01
      • 2016-05-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多