【问题标题】:absolute is not available for the grandchildren of flex elements?绝对不能用于 flex 元素的子孙?
【发布时间】:2022-11-01 12:14:21
【问题描述】:

如何将.top_box 固定在.content 的头部?

使用当前代码,.top_box 始终与.content 一起滚动。

.wrapper {
    height: 160px;
    display: flex;
    flex-direction: column;
}
.title_container {
    background: pink;
}
.content {
    height: 0;
    flex: auto;
    position: relative;

    overflow-y: auto;
    overflow-x: hidden;
    background-color: bisque;
}
.top_box {
    position: absolute;
    top: 0;
    left: 0;
    width: 300px;
    height: 16px;
    background: royalblue;
}

.scroll_fill {
    height: 500px;
}
<div class="wrapper">
    <div class="title_container">anyString</div>
    <div class="content">
        <div class="top_box"></div>
        <div class="scroll_fill"></div>
    </div>
</div>

【问题讨论】:

    标签: css


    【解决方案1】:

    您只需更改代码中 HTML 元素的顺序,然后在 .item 之前写入 .top。如果你这样做,你也可以删除大部分 CSS,因为它是不必要的。

    这是一个完整的例子:

    .box1 {
        height: 600px;
        display: flex;
        flex-direction: column;
    }
    .box2 {
        background: pink;
    }
    .box3 {
        background-color: red;
    }
    .top {
        width: 300px;
        height: 5px;
        background: blue;
    }
    .item {
        height: 1000px;
    }
    <div class="box1">
        <div class="box2">anyString</div>
        <div class="box3">
            <div class="top"></div>
            <div class="item"></div>
        </div>
    </div>
        

    还有其他一些事情:我不建议只使用 divs 并将它们命名为盒子1,盒子2,盒子3,....相反,给他们起名字来描述他们的用途和意义,比如包装器,top_container,bottom_container,top_item,内容,...CSS Naming Conventions

    您还可以使用具有语义含义的特定标签:Sematic HTML5 Elements

    希望有帮助

    【讨论】:

      【解决方案2】:

      .wrapper {
          height: 160px;
          display: flex;
          flex-direction: column;
      }
      .title_container {
          background: pink;
      }
      .content {
          height: 0;
          flex: auto;
          position: relative;
          overflow: hidden;
          background-color: bisque;
      }
      .contentInner {
          height: 100%;
          width: 100%;
          overflow-y: auto;
          overflow-x: hidden;
      }
      .top_box {
          position: absolute;
          top: 0;
          left: 0;
          width: 300px;
          height: 16px;
          background: royalblue;
      }
      .scroll_fill {
          height: 500px;
      }
      <div class="wrapper">
          <div class="title_container">anyString</div>
          <div class="content">
              <div class="top_box"></div>
              <div class="contentInner">
                  <div class="scroll_fill"></div>
              </div>
          </div>
      </div>

      【讨论】:

        猜你喜欢
        • 2020-09-08
        • 2019-07-01
        • 2019-01-02
        • 2014-04-06
        • 1970-01-01
        • 1970-01-01
        • 2018-02-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多