是否可以使用CSS更改flex项的嵌套结构(取决于@media)?

时间:2017-01-14 19:31:31

标签: html css flexbox

我有一个双栏布局,左边是侧边栏,右边是地图。侧边栏有两个盒子;一个用于搜索输入,一个用于结果列表。所以在桌面上它看起来像这样:

+--------------+---------------------+
| search input |                     |
+--------------+           map       |
|  results     |                     |
|   ...        |                     |
+--------------+---------------------+

在移动设备上,我希望所有内容都显示在一个列中,但是搜索输入和结果之间存在地图,因此它比简单的flex-direction / order更改更具结构性变化:

+------------------------------------+
|          search input              |
+------------------------------------+
|                                    |
|               map                  |
|                                    |
+------------------------------------+
|           results                  |
|             ...                    |
+------------------------------------+

这可能吗?

1 个答案:

答案 0 :(得分:3)

没有JavaScript重新排序的条件是所有项目都是兄弟姐妹:

<div class="wrap">
  <div            > 1. sidebar </div>
  <div class="map"> 2. map </div>
  <div            > 3. also sidebar </div>
  <div            > 4. still sidebar </div>
</div>

flexbox之前,这是使用浮点数实现的:

body {margin: 0; padding: 0;}
.wrap {
  overflow: hidden;
  padding: 1rem;
  background-color: #999;
  min-height: 100vh;
  box-sizing: border-box;
}
.wrap > * {
  width: 25%;
  float: left;
  background-color: #eee;
  background-clip: content-box;  
  box-sizing: border-box;
  padding: 1rem;
  min-height: 6rem;
}
.map {
  float: right;
  width: 75%;
  min-height: calc(100vh - 2rem);
}
@media (max-width: 800px) {
  .map {
    min-height: 50vh;
  }
  .wrap > *{
    float: none;
    width: 100%;
  }
}
<div class="wrap">
  <div>1. sidebar</div>
  <div class="map">2. map</div>
  <div>3. also sidebar</div>
  <div>4. still sidebar</div>
</div>

现在,您可以使用flexbox

,使用order

body {margin: 0; padding: 0;}
.wrap {
  height: 100vh;
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  padding: 1rem;
  background-color: #999;
  box-sizing: border-box;
}
.wrap > * {
  width: 25%;
  float: left;
  background-color: #eee;
  background-clip: content-box;
  box-sizing: border-box;
  padding: 1rem;
  min-height: 6rem;
}
.map {
  order: 999;
  width: 75%;
  min-height: 100%;
}
@media (max-width: 800px) {
  .wrap {
     flex-wrap: nowrap;
     height: auto;
     min-height: 100vh;
   }
  .wrap > * {
    width: 100%;
  }
  .map{
    order: unset;
    width: 100%;
    min-height: 50vh;
  }
}

@media (max-height: 480px) {
  .wrap {
    height: 480px;
  }
}
<div class="wrap">
  <div>1. sidebar</div>
  <div class="map">2. map</div>
  <div>3. also sidebar</div>
  <div>4. still sidebar</div>
</div>