从中断溢出自动停止flex align-items

时间:2017-06-20 19:49:28

标签: html css css3 flexbox

我正在使用Flexboxes来创建以页面为中心的内容。但是,如果文本溢出,我希望它使用overflow-x: auto滚动条。

显然,这不起作用,我已经在我的桌子上敲了一会儿。我不得不在这里找到一些简单的东西,但我不能为我的生活弄清楚这一点。

在摘录中,第一个框是我真正喜欢的第二个框,除了flexbox打破了它。

.flex-container{
      height: 100%;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      margin-top: 20px;
    }
    
.scrollable-content{
  overflow-x: auto;
}
<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
  </head>

  <body>
    <div class="scrollable-content">
      <div style="background-color: red;width: 700px;height: 50px">I might be too wide on small screens, but you have a scrollbar if I am!</div>
    </div>
    
    <div class="flex-container">
      <div class="scrollable-content">
        <div style="background-color: red;width: 700px;height: 50px">I might be too wide on small screens, but you have a scrollbar if I am!</div>
    </div>
    </div>
  </body>

</html>

1 个答案:

答案 0 :(得分:3)

通常,对于要滚动overflow: auto的元素,它需要宽度(或高度)。

普通块元素具有默认宽度(100%),默认情况下将滚动,但弹性项目会调整为内容,而不会。

在这种情况下,当弹性方向为column时,您需要将max-width: 100%(或width: 100%)添加到scrollable-content

.flex-container{
      height: 100%;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      margin-top: 20px;
    }
    
.scrollable-content{
  max-width: 100%;
  overflow-x: auto;
}
    <div class="flex-container">
      <div class="scrollable-content">
        <div style="background-color: red;width: 300px;height: 50px">I'm small and centered</div>
      </div>
    </div>
    
    <div class="flex-container">
      <div class="scrollable-content">
        <div style="background-color: red;width: 700px;height: 50px">I might be too wide on small screens, but you have a scrollbar if I am!</div>
      </div>
    </div>