首页 > 解决方案 > 相对定位的元素不占用其子元素的高度

问题描述

我正在使用带有以下html和scss的css构建一个小进度条(它只是scss,因为我正在使用嵌套)

html:

<div class="first">
  <div class="first__progress-bar-container"/>
  <div class="first__progress-bar"/>
  <div class="first__content-section">
    <div>content</div>
    <div>content</div>
    <div>content</div>
  </div>  
</div>
<div class="second">more content</div>

scss:

.first {
  position: relative;
  height: 10px;
  width: 1000px;

  &__progress-bar-container {
    position: absolute;
    background: #eee;
    height: 10px;
    width: 100%;
    z-index: 1
  }

  &__progress-bar {
    position: absolute;
    z-index: 2;
    height: 10px;
    background: linear-gradient(to right, red, blue);
    border-radius: 0 5px 5px 0;
    width: 50%;
  }
}

也可以使用这个codepen

如果我在浏览器中看到结果,文本"more content"就位于所有.content-section内容之上。我预计这.second会出现在它之后.content-section而不是在它之上。

为什么子元素不.content-section被评估为父元素的高度.first

后续问题是,我怎样才能让它"more content"出现在第一部分内容之后而不是在它之上?

标签: htmlcss

解决方案


我已经稍微更改了标记,假设您想将进度条放在进度条容器中。如果进度条位于进度条容器内,则不再需要相对定位和绝对定位。从 .first 中删除了高度,以便 .first 的大小是内容的大小。

SCSS:

.first {

  width: 1000px;
  background-color:grey;

  &__progress-bar-container {
    background: #eee;
    height: 10px;
    width: 100%;
  }

  &__progress-bar {

    height: 10px;
    background-image: linear-gradient(to right, red, blue);
    border-radius: 0 5px 5px 0;
    width: 50%;
  }
}

HTML:

<div class="first">
  <div class="first__progress-bar-container">
    <div class="first__progress-bar"></div>
  </div>
  <div class="content-section">
    <div>content</div>
    <div>content</div>
    <div>content</div>
  </div>  
</div>
<div class="second"> more content</div>

推荐阅读