【问题标题】:CSS position relative and element heightCSS 相对位置和元素高度
【发布时间】:2019-01-26 15:09:04
【问题描述】:

我在另一个元素下方有一个元素,我使用相对位置将底部元素向上拖动一点,以便它覆盖顶部元素。

paperOverlay 元素是页面上的最后一个元素,垂直方向,我希望它延伸到浏览器窗口的底部。但是,元素位置的相对轻推会在底部留下等量的空白。有什么办法可以避免吗?

HTML 看起来像:

div class="container">
    <div class="homePage">
        <!-- some content -->
    </div>
    <div class="paperOverlay" style="position: relative; top: -70px;">
        <!-- some more content -->
    </div>
</div>

CSS 看起来像:

div.container 
{ 
    width: 960px;
    margin: 0 auto;
}

div.homePage 
{ 
    width: 800px;
    height: 500px;
}

div.paperOverlay
{
    width: 960px;
    min-height: 400px;
    background: url('Images/Overlay.png') no-repeat top center;
}

基本上,底层是白色背景,顶部有撕纸边缘效果。目标是让撕裂的纸张边缘稍微覆盖其上方元素的底部。我确实按照下面的建议尝试了margin-top: -70px,它固定了高度,但现在顶部元素中的元素位于叠加层的顶部,我希望叠加层位于顶部。

【问题讨论】:

    标签: css


    【解决方案1】:

    您可以尝试负边距而不是相对定位吗?另外,您能否再解释一下为什么需要这样做并发布您的 css 以便我们更好地提出解决方案?

    【讨论】:

    • 负边距有效,除了底部元素现在分层在顶部元素之下。有什么想法吗?另外,现在发布 CSS。
    • 现在将您的元素设置为相对位置(无需实际更改)并增加其 z-index。 .paperOverlay { z-index: 2;位置:相对; }
    【解决方案2】:

    尝试设置 paperOverlay 元素的高度。应该是实际高度减去相对移动量。

    【讨论】:

      【解决方案3】:

      我确实按照下面的建议尝试了 margin-top: -70px 并固定了高度,但现在顶部元素中的元素位于叠加层的顶部,我希望叠加层位于顶部。

      试试这个:

      div.container 
      { 
          margin: 0 auto;
          width: 960px;
      }
      
      div.homePage 
      { 
          height: 500px;
          position: relative;
          width: 800px;
          z-index: 1;
      }
      
      div.paperOverlay
      {
          background: url('Images/Overlay.png') no-repeat top center;        
          min-height: 400px;
          position: relative;
          top: -70px;
          /* you can optionally use bottom: 70px; rather than top: -70px */
          width: 960px;
          z-index: 2;
      }
      

      使用位置:相对;在这两个元素上设置 z-index 应该在顶部元素的顶部获得覆盖,而不是相反。

      您可能还想尝试使用 display: block;在所有需要固定宽度/高度的元素上(尤其是 div 和其他需要固定宽度/高度的容器,如锚点或列表项),以防止折叠。它通常会调整非块级元素的大小以适应其内容,否则忽略宽度和高度规则。

      【讨论】:

        【解决方案4】:

        使用“vh”单位对我有用。我无法使用height: calc(100%-50px)

        #main-nav{
        
            width: 55px;
            background-color: white;
        
            transition: 400ms;
            height: calc(100vh - 50px);
        }
        

        【讨论】:

          猜你喜欢
          • 2021-12-29
          • 1970-01-01
          • 2010-12-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-12-13
          • 1970-01-01
          相关资源
          最近更新 更多