流DIV使它们使用自由空间而不仅仅是堆叠

时间:2017-10-30 18:49:08

标签: html5 css3

我有四个div。

Div 2是div 1的高度的一半,div 3& 4是div 2的高度的一半。

在大型显示器上,div的位置很好:

---------------- ---------- -------- --------
|              | |  Div 2 | | Div 3| | Div 4 |
|    Div 1     | |________|  -------  -------
|              | 
|              |
----------------

在较小的屏幕上,我想要以下布局:

---------------- ----------
|              | |  Div 2 |
|    Div 1     | |________|
|              | |  Div 3 |
|              | ----------
---------------- | Div 4  |

即。 div 3和4位于div 2下。

但相反,它们被放置在div 1下:

---------------- ----------
|              | |  Div 2 |
|    Div 1     | |________|
|              | 
|              |
----------------
-------- --------
| Div 3| | Div 4 |
 -------  -------

是否有可能以某种方式获得第二种选择?在我自己的尝试中,我从来没有使用大屏幕和较小的屏幕替代品来使用相同的代码。

1 个答案:

答案 0 :(得分:1)

可以使用CSS属性flexboxMDN reference)来实现这一目标。请参阅下面的示例(全屏并拉伸屏幕)。

在首先启动移动设备时,您可以按照自己的方式进行操作,并且通过设置media queries,您可以轻松修改框的可视层次结构。首先,将display: flex;放在包装器div上,然后放在所需的断点上(此处为480px),在display: flex;上添加另一个.inner-wrapper

注意:这只是一个快速设置,有很多方法可以做到这一点。



.wrapper {
  width: 100%;
  height: 100vh;
  display: flex;
}

.inner-wrapper {
  width: 50%;
}

.box-large {
  width: 50%;
  height: 50%;
}

.box {
  width: 100%;
  height: 25%;
}

.box-small {
  width: 100%;
  height: 12.5%;
}

@media screen and (min-width: 480px) {
  .inner-wrapper {
    display: flex;
  }
}

/* Visual stuff */

body {
  margin: 0;
  padding: 0;
}

.box-one {
  background-color: red;
}

.box-two {
  background-color: blue;
}

.box-three {
  background-color: green;
}

.box-four {
  background-color: yellow;
}

<div class="wrapper">
  <div class="box-one box-large">red</div>
  <div class="inner-wrapper">
    <div class="box-two box">blue</div>
    <div class="box-three box-small">green</div>
    <div class="box-four box-small">yellow</div>
  </div>

</div>
&#13;
&#13;
&#13;