【问题标题】:A 2x2 grid in flexboxflexbox 中的 2x2 网格
【发布时间】:2019-01-09 15:27:15
【问题描述】:

我做了一个 1 x 4 网格的演示; 1 行 4 列。它工作正常,但我希望它在用户屏幕小于720px 时显示 2 x 2 网格。我尝试使用像this这样的媒体查询:

body, * {
  padding: 0;
  margin: 0;
}

.wrapper {
  display: flex;
}

.box {
  height: 100px;
  border: 1px solid;
  box-sizing: border-box;
  flex: 1;
  background-color: grey;
}


 @media only screen and (min-width: 360px) and (max-width: 720px) {
   .box {
       background-color: blue;
   }
 }

屏幕尺寸小于 720 像素时如何更改布局?

斌:https://jsbin.com/xudihuxato/edit?html,css,output

【问题讨论】:

  • 我只想指出选择器body, * 是多余的,因为它同时选择了主体...和所有内容(包括主体)。所以就做*

标签: jquery html css flexbox


【解决方案1】:

@media only screen and (min-width: 360px) and (max-width: 720px) {

  .wrapper {
    flex-wrap: wrap;
  }

  .box {
    flex-basis: 34%;
    background-color: blue;
  }

}

在您的主代码中,您将弹性项目设置为flex: 1。这是相当于的简写:

  • flex-grow: 1
  • flex-shrink: 1
  • flex-basis: 0

基本上,这会占用行上的整个空间并将其平均分配给四个项目。

要使项目分成 2x2 网格,请在媒体查询中设置以下规则:

  1. 允许使用flex-wrap: wrap 包装项目。默认为nowrap

  2. flex-basis 设置为 50%,因此每行只能容纳两个项目。

    如果您想为边框、填充和/或边距腾出空间,请将flex-basis 设置为 34%(或类似的值)。

    在主规则中定义flex-grow: 1 后,flex-basis 无需为 50%,由于边框、填充或边距,这可能导致每行一个项目。

    由于flex-grow 将占用行上的可用空间,flex-basis 只需大到足以强制执行换行即可。

    在这种情况下,flex-basis: 34% 有足够的空间用于边距,但没有足够的空间用于每行的第三个项目。

【讨论】:

  • 什么是 flex-basis 34%
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-05-25
  • 2016-06-30
  • 2018-08-24
  • 2014-03-31
  • 2012-12-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多