html/css responsive 3-column layout - stack right column below left column

心已入冬 提交于 2019-11-28 02:24:51

You can't accomplish that with Flexbox, unless setting fixed height's all over.

Here is a solution that combine Flexbox with float, and use a media query to swap between the two, when on narrower screens.

Note, when using percent based width combined with fixed margins, it can at some point cause the item to wrap. Use CSS Calc to avoid that, as showed in the answer.

Stack snippet

.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>

I could come up only with old good floats, no flexboxes at all. If you don't have to use flexboxes and you are interested, with pretty light hustle it might look like this (snap point is 700px):

* {
     box-sizing: border-box;
}
.container {
    width:90%; 
    height:200px; 
    margin:0px auto;
}
div > div {
  background-color: orange;
  float: left;
  color: white;
  text-align: center;
  padding: 1em;
}
.leftsidebar {
    width: 20%; 
    height: 200px;  
    margin-top: 15px;
}
.middle{
    width:56%;  
    margin: 15px 2% 0%;  
    height:415px; 
}
.rightsidebar {
    width: 20%; 
    height: 200px; 
    margin-top: 15px;
}
@media (max-width: 700px) {
    div > div:nth-of-type(2n + 1) {
        width: 33%;
    }  
    div > div:nth-of-type(2n) {  
       float: right;
       width: 65%; 
       margin-right: 0%;
    } 
}
<div class="container">

<div class="leftsidebar">left </div>
<div class="middle">middle </div>
<div class="rightsidebar">right </div>
</div>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!