【问题标题】:flexbox justify-content causes overflow: auto not work correctlyflexbox justify-content 导致溢出:自动无法正常工作
【发布时间】:2022-01-17 23:39:28
【问题描述】:

我有一个容器div,它的内容可以垂直增长。我使用overflow-y: auto 作为容器以使我的页面看起来不错。但是当内容的高度小于容器的高度时,我需要将所有内容放在中心。所以我使用 flexbox 来做到这一点。但问题是我无法完全滚动查看内容的顶部。


这里是有问题的代码的一个简单示例:

<html lang="en">
  <head>
    <style>
      .container {
        width: 20rem;
        height: 20rem;
        background-color: red;

        display: flex;
        justify-content: center;
        flex-direction: column;
        align-items: center;

        overflow-y: auto;

      }
      .child {
        width: 10rem;
        height: 40rem;
        background-color: blue;
        flex-shrink: 0;
      }
      .top {
        width: 1rem;
        height: 1rem;
        background-color: green;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <div class="child">
        <div class="top"></div>
      </div>
    </div>
  </body>
</html>

【问题讨论】:

    标签: html css web flexbox frontend


    【解决方案1】:

    解决此问题的方法之一是使用 flex-container 中元素的相反顺序,即在您的情况下,使用 flex-direction: column-reverse 而不是 flex-direction: column

    下面的示例 #1:

    .container {
      width: 20rem;
      height: 20rem;
      background-color: red;
      display: flex;
      justify-content: center;
      flex-direction: column-reverse;
      align-items: center;
      overflow-y: auto;
    }
    
    .child {
      width: 10rem;
      min-height: 0;
      height: 40rem;
      background-color: blue;
      flex-shrink: 0;
      max-height: 150%;
    }
    
    .top {
      width: 1rem;
      height: 1rem;
      background-color: green;
    }
    <div class="container">
      <div class="child">
        <div class="top">test</div>
      </div>
    </div>

    第二种方案是考虑使用居中对齐,也可以使用justify-content: space-between和伪元素::after::before

    下面的示例 #2:

    .container {
      width: 20rem;
      height: 20rem;
      background-color: red;
      display: flex;
      justify-content: space-between;
      flex-direction: column;
      align-items: center;
      overflow-y: auto;
    }
    
    .container::before,
    .container::after {
      content: '';
    }
    
    .child {
      width: 10rem;
      min-height: 0;
      height: 40rem;
      background-color: blue;
      flex-shrink: 0;
      max-height: 150%;
    }
    
    .top {
      width: 1rem;
      height: 1rem;
      background-color: green;
    }
    <div class="container">
      <div class="child">
        <div class="top">test222</div>
      </div>
    </div>

    【讨论】:

    • ::before::after 伪元素完美地解决了我的问题。谢谢
    猜你喜欢
    • 2017-12-23
    • 2017-01-26
    • 2022-01-19
    • 2016-03-13
    • 2018-03-25
    • 2017-05-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多