代码之家  ›  专栏  ›  技术社区  ›  user944513

flexbox中的2x2网格

  •  2
  • user944513  · 技术社区  · 8 年前

    我做了一个演示,其中我制作了一个1×4的网格;1行4列。它工作得很好,但是当用户屏幕小于 720px . 我尝试使用媒体查询 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;
       }
     }
    

    当屏幕大小小于720px时,如何更改布局?

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

    1 回复  |  直到 8 年前
        1
  •  1
  •   Michael Benjamin William Falcon    8 年前

    @media only screen and (min-width: 360px) and (max-width: 720px) {
    
      .wrapper {
        flex-wrap: wrap;
      }
    
      .box {
        flex-basis: 34%;
        background-color: blue;
      }
    
    }

    在主代码中,flex项设置为 flex: 1 . 这是相当于:

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

    从本质上讲,这会占用行上的整个空间,并在四个项目之间平均分配。

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

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

    2. 设置 flex-basis 到50%,所以每行只能容纳两个项目。

      如果要为边框、填充和/或页边距留出空间,请设置 伸缩基准值 34%(或类似的)。

      柔性增长:1 在主规则中定义,不需要 伸缩基准值 为50%,由于边框、填充或边距的原因,每行可能会产生一个项目。

      自从 flex-grow 将消耗行上的可用空间, 伸缩基准值

      flex-basis: 34%