4 Floating DIVs that respond symmetrically on narrowing screens with CSS

时光总嘲笑我的痴心妄想 提交于 2019-12-06 09:41:12

Group [3] and [4] together in a div (and [1] and [2] if you desire). Give it a max width, but auto height. That way, when the screen narrows, the two divs should move together side by side, but jump down when the screen gets narrower.

ex:

.contain {
    max-width:256px;
    height:auto;
}

<div class="contain">
    <div class="div3">contents</div>
    <div class="div4">contents</div>
</contain>

Here is one way of doing it using media queries.

The trick is to pick a suitable break point for max-width, for example, 610px, and then use the nth-child selected to clear the float at every 3rd child element beginning with the 3rd one.

Reference: https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries

.box {
  float: left;
  width: 128px;
  height: 128px;
  background-color: grey;
  margin: 10px;
  box-sizing: border-box;
  border: 2px solid black;
}
.container-box {
  border: 1px dotted blue;
  overflow: auto;
  box-sizing: borderbox;
}
@media (max-width: 610px) {
  .box {
    background-color: yellow;
  }
  .box:nth-child(2n+3) {
    background-color: red;
    clear: left;
  }
}
<div class="container-box">
  <div class="box">1</div>
  <div class="box">2</div>
  <div class="box">3</div>
  <div class="box">4</div>
</div>

Try wrapping 2 divs into a container div then set the width of that container div to be twice the size of each regular div.

<div class="container-box">
    <div class="box">1</div>
    <div class="box">2</div>
</div>
<div class="container-box">
    <div class="box">3</div>
    <div class="box">4</div>
</div>

.box {    
    float:left; 
    width:128px;
    height:128px;
    background: grey;
}

.container-box {
    float: left;
    width: 256px;
    height: 128px;
}

Here's a link to a fiddle: https://jsfiddle.net/wfhk1fak/1/

Hope this helps.

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