首页 > 解决方案 > 使用 CSS Flexbox 构建堆叠布局

问题描述

我有一个工作面试的技术测试,我正在为应该是一个简单的布局而苦苦挣扎!

我需要一个两列设计,其中 div 按以下方式堆叠在一起:

所需的布局

然后对于较小的屏幕将更改为:

在此处输入图像描述

我以为我很了解 flexbox,但事实证明我显然不知道,我能得到的最接近的(这是不近的......)是

在此处输入图像描述

使用

 <head>
  <style>
  .container{
    width:600px;
    min-height:300px;
    background-color: blue;
    display:flex;
    flex-wrap: wrap;
  }
  .small{
    width: 100px;
    height:100px;
    background-color: darkgoldenrod;
    margin:20px;
  }
  .big{
    width: 250px;
    height:250px;
    background-color: green;
    margin:20px;
  }
  </style>
</head>
<body>
<div class="container">
    <div class="big">Widget 1</div>
    <div class="small">Widget 2</div>
    <div class="small">Widget 3</div>
    <div class="big">Widget 4</div>
    <div class="small">Widget 5</div>
    <div class="small">Widget </div>
</div>
</body>

我已经搜索了几个小时,但我无法接近任何东西!谁能指出我正确的方向?

标签: csslayoutflexboxstyles

解决方案


您可以使用flexbox order 属性对移动视图上的项目进行重新排序。对于桌面视图,请查看CSS 媒体查询,为不同的视口提供不同的样式。

.grid-container {
  background: blue;
  display: flex;
  flex-direction: column;
  padding: 10px;
}

.widget {
  width: 100px;
  height:100px;
  margin: 10px;
  background-color: darkgoldenrod;
}

.green {
  background-color: green;
}

.item1 {
  order: 1;
}

.item2 {
  order: 2;
}

.item3 {
  order: 4;
}

.item4 {
  order: 3;
}

.item5 {
  order: 5;
}

.item6 {
  order: 6;
}
<div class="grid-container">
  <div class="widget item1 green">1</div>
  <div class="widget item2">2</div>
  <div class="widget item3">3</div>
  <div class="widget item4 green">4</div>
  <div class="widget item5">5</div>
  <div class="widget item6">6</div>
</div>


推荐阅读