响应式两列布局:在其他列之间移动一列

5 html css flexbox responsive-design

我有一个响应式网站,在大型浏览器窗口中具有两列布局。两列布局目前是使用浮动实现的。在较小的屏幕上,我只想只有一栏。另一列的内容应显示在主列的两个元素之间,如下所示:

小样

<div class="two-columns">
  <div class="main-column">
    <div class="red-element"></div>
    <div class="yellow-element"></div>
  </div>
  <div class="sidebar-column">
    <div class="green-element"></div>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

我尝试使用基于 Flex-box 的方法,基本上就是这个问题中描述的方法,但在 Safari中flex-basis似乎仍然不受支持。适当的 Safari 支持是必须的,因为 Safari 是我的访问者的主要浏览器。flex-directioncolumn

有没有一种方法可以仅使用 CSS 来实现这一点,而不必在我的标记中放置两次绿色元素?

Mic*_*l_B 3

这是使用一个弹性容器的通用解决方案:

<div class="container">
    <div class="box"> ... </div><!-- red box -->
    <div class="box"> ... </div><!-- green box -->
    <div class="box"> ... </div><!-- yellow box -->
</div>
Run Code Online (Sandbox Code Playgroud)

从小屏幕开始(没有特殊原因),将它们堆叠在一列中:

.container {
    display: flex;
    flex-direction: column;
}

.box {
    height: 100px;
    width: 100%;
}
Run Code Online (Sandbox Code Playgroud)

重新排列布局以适应更宽的屏幕:

@media (min-width: 800px) {

   .container {
        flex-direction: row;
        flex-wrap: wrap;
    }

    .box {
        flex-basis: 45%;
    }
}
Run Code Online (Sandbox Code Playgroud)

在宽度超过 800 像素的屏幕上,容器将项目排成一行并启用换行。每个框都有足够大的宽度 ( flex-basis),仅两个框可以排在一条线上。


完整演示:

<div class="container">
    <div class="box"> ... </div><!-- red box -->
    <div class="box"> ... </div><!-- green box -->
    <div class="box"> ... </div><!-- yellow box -->
</div>
Run Code Online (Sandbox Code Playgroud)
.container {
    display: flex;
    flex-direction: column;
}

.box {
    height: 100px;
    width: 100%;
}
Run Code Online (Sandbox Code Playgroud)

jsFiddle


从你的问题来看:

...但flex-basisSafari 似乎仍然不flex-direction支持column

我不确定这是否正确(caniuse.com)。

但是,您始终可以使用widthheight属性代替flex-basis(更多详细信息:Flex-basis 和 width 之间的区别是什么?)。