如何在移动布局中从上到下移动 div?

How can I move a div from top to bottom on mobile layouts?

我正在使用 Bootstrap 4,但如果它适用于版本 3,它应该适用于 v4。

我在一列中有 2 个 div,如下所示:

<div class="row">
    <div class="col-xs-12">
        <div>TOP ON DESKTOP, BOTTOM ON MOBILE</div>
        <div>BOTTOM ON DESKTOP, TOP ON MOBILE</div>
    </div>
</div>

有没有办法让 div 在移动设备上交换?我不想在这里使用任何 JavaScript;如果可能,我只想使用 Bootstrap 类。

如果 Bootstrap 不可行,那么 CSS-请。

.col-xs-12 { height: 200px; position:relative; }
.col-xs-12 div { position:absolute; top:0; left: 0; width:100%; }
.col-xs-12 div:last-child { top: auto; bottom: 0; }

@media (max-width: 480px) {
    .col-xs-12 div { top:auto; bottom:0; }
    .col-xs-12 div:last-child { top: 0; bottom: auto; }
}

这可以使用 CSS' flexbox.

来实现
  • 添加具有以下属性的新选择器 .col-xs-12
    • display: flex; 告诉 children 使用 flexbox 模型
    • flex-direction: column-reverse; 将确保 children 从下到上流动(而不是默认的从左到右)

运行 以下代码段全屏显示并调整大小 window 以查看元素顺序的变化。

@media only screen and (max-width: 960px) {
  .col-xs-12 {
    display: flex;
    flex-direction: column-reverse;
  }
}
<div class="row">
  <div class="col-xs-12">
    <div>TOP ON DESKTOP, BOTTOM ON MOBILE</div>
    <div>BOTTOM ON DESKTOP, TOP ON MOBILE</div>
  </div>
</div>

一个Bootstrap方法

这也可以使用Bootstrap来实现:

  • 将以下 类 添加到容器中:
    • d-flex 让容器使用 flexbox
    • flex-column-reverse 在小屏幕上以相反的顺序排列 children
    • flex-sm-column 在大屏幕上按正常顺序排列 children

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<div class="row">
  <div class="col-xs-12 d-flex flex-column-reverse flex-sm-column">
    <div>TOP ON DESKTOP, BOTTOM ON MOBILE</div>
    <div>BOTTOM ON DESKTOP, TOP ON MOBILE</div>
  </div>
</div>

以下代码对我有用:

@media only screen and (max-width: 768px) {
  .xs-column-reverse {
    display: flex;
    flex-direction: column-reverse;
  }
}
<div class="row">
  <div class="col-xs-12 xs-column-reverse">
    <div>TOP ON DESKTOP, BOTTOM ON MOBILE</div>
    <div>BOTTOM ON DESKTOP, TOP ON MOBILE</div>
  </div>
</div>