4个浮动DIV在CSS缩小屏幕上对称响应 [英] 4 Floating DIVs that respond symmetrically on narrowing screens with CSS

查看:50
本文介绍了4个浮动DIV在CSS缩小屏幕上对称响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[1] [2] [3] [4]

[ 1 ] [ 2 ] [ 3 ] [ 4 ]

我有四个使用简单CSS左移的DIV(上方):float:left;宽度:128像素;高度:128像素

I have four DIVs floating left (above), using simple CSS: float:left; width:128px;height:128px

当我缩小屏幕范围时,最后一个DIV会正确跳到下一行:

As I narrow the screen, the last DIV jumps correctly onto the next line:

[1] [2] [3]

[ 1 ] [ 2 ] [ 3 ]

[4]

但是我真正想要的是最后两个块跳到下一行,以保持外观对称:

But what I'd really like is for the last two blocks to jump onto the next line in order to keep the look symmetrical:

[1] [2]

[3] [4]

然后,当屏幕进一步缩小时,这些块将一个堆叠在另一个之上:

And when the screen narrow further, the blocks stack one above the other:

[1]

[2]

[3]

[4]

推荐答案

这是使用媒体查询的一种方法.

Here is one way of doing it using media queries.

诀窍是为最大宽度选择合适的断点,例如610px,然后使用选择的 nth-child 清除每个从第三个元素开始的第三个子元素.

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.

参考: https://developer.mozilla.org/zh-CN/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>

这篇关于4个浮动DIV在CSS缩小屏幕上对称响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆