【问题标题】:CSS positioning with flex of divs in different orders [duplicate]以不同顺序使用div的flex进行CSS定位[重复]
【发布时间】:2018-08-08 21:45:22
【问题描述】:

我正在尝试使用 Flexbox 获得特定的 css 布局(作为 css 网格布局的后备),但实际上我不确定是否有可能获得我的想法。

我有以下 HTML 结构:

<div class="container">
    <div class="div1">DIV 1</div>
    <div class="div2">DIV 2</div>
    <div class="div3">DIV 3</div>
</div>

这就是我想要实现的(使用 css 网格很容易):

除此之外,我希望 div 1 和 3 固定在滚动上,并且 div2 内容可以滚动。

我只是想知道是否有可能完成这项工作;我尝试了很多 flex 设置,但我无法获得它。

【问题讨论】:

    标签: html css flexbox css-grid


    【解决方案1】:

    如果您的容器具有固定高度(我假设它是视口的 100%),您可以使用带有 wrap 和 order 的列方向来实现您的布局:

    html, body {
      margin:0;
      height:100%;
      color:white;
    }
    .container {
      height:100%;
      display: flex;
      flex-direction: column;
      flex-wrap: wrap;
    }
    
    .div1,
    .div3 {
      height: 50%;
      width: 30%;
    }
    
    .div1 {
      background: red;
    }
    
    .div2 {
      max-height:100%; /* make overflow scroll */
      overflow:auto;
      flex-grow: 1;  /* make div fill height */
      width: 70%;
      order: 3;      /* put this div at the end */
      background: grey;
    }
    
    .div3 {
      order: 2;       /* put this div below div1 */
      background: blue;
    }
    <div class="container">
      <div class="div1">DIV 1</div>
      <div class="div2">DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br>DIV 2<br></div>
      <div class="div3">DIV 3</div>
    </div>

    【讨论】:

    • ...我必须承认:我现在感觉很愚蠢... :) 最后很容易...谢谢@Pete
    • 没问题,很高兴它有帮助:)
    • Hello @Pete ...抱歉再次打扰,但我刚刚注意到上面的代码在 Chrome 中不起作用 - 三个 div 在一行中彼此并排显示,而在 Firefox、Edge 和 Opera 中看起来还不错。实际上这很奇怪,因为当我调整浏览器大小并再次全屏显示时,它会按预期显示。当我刷新页面时,三个 div 再次返回并排成一行……嗯,这很奇怪……
    猜你喜欢
    • 2020-05-24
    • 2016-04-02
    • 1970-01-01
    • 1970-01-01
    • 2018-10-21
    • 1970-01-01
    • 2021-11-09
    • 2023-03-31
    • 1970-01-01
    相关资源
    最近更新 更多