我试图在较小的屏幕上将3列布局的右列移到左列下方。现在,右列沿正确的方向移动,但它悬挂在中间列的下方。

我创建了这个问题的基本模拟。请注意,中间列将始终比左右列长,如下所示。

<style>
  .container {
    max-width:1280px;
    width:100%;
    height:200px;
    margin-left:auto;
    margin-right:auto;
    display:flex;
    flex-wrap: wrap;
  }

  .leftsidebar {
    width:20%;
    height:200px;
    background-color:gray;
    margin-top:15px;
  }

 .middle {
    width:57%;
    background-color:blue;
    margin-left:15px;
    margin-right:15px;
    height:800px;
    margin-top:15px;
  }

 .rightsidebar {
    width:20%;
    background-color:orange;
    height:200px;
    margin-top:15px;
  }
</style>

<div class="container">
  <div class="leftsidebar">left</div>
  <div class="middle">middle</div>
  <div class="rightsidebar">right</div>
</div>

最佳答案

除非将固定高度全部设置好,否则您无法使用Flexbox做到这一点。

这是将Flexbox与float结合使用的解决方案,并且在较窄的屏幕上时,可以使用媒体查询在两者之间进行交换。

请注意,当使用基于百分比的宽度和固定边距组合时,它可能在某些时候导致包裹。如答案所示,使用CSS Calc可以避免这种情况。

堆栈片段



.container {
  max-width: 1280px;
  height: 200px;
  margin: 0 auto;
  display: flex;
}

.leftsidebar, .rightsidebar {
  width: 20%;
  background-color: gray;
  margin-top: 15px;
}
.rightsidebar {
  background-color: orange;
  clear: left;
}

.middle {
  width: calc(60% - 30px);          /*  calc for margin  */
  background-color: blue;
  margin: 15px 15px 0 15px;
  height: 800px;
}

@media (max-width: 600px) {
  .container {
    display: block;
  }
  .leftsidebar, .rightsidebar {
    height: 200px;
    float: left;
  }
  .middle {
    width: calc(80% - 30px);          /*  calc for margin  */
    float: right;
  }
}

<div class="container">
  <div class="leftsidebar">left </div>
  <div class="middle">middle </div>
  <div class="rightsidebar">right </div>
</div>

10-02 17:52