css:网格布局

93 阅读1分钟

一、效果

动图.gif

flex布局是一维布局,它的关键是主轴,网格布局是二维的,容器具有行和列

二、基础布局

      .container {
        display: grid;
        grid-template-columns: 100px 100px 100px;
        grid-template-rows: 50px 50px;
      }
      .container div img {
        width: 100%;
        height: 100%;
      }
      .container div:nth-of-type(1) {
        background-color: greenyellow;
      }
      .container div:nth-of-type(2) {
        background-color: deeppink;
      }
      .container div:nth-of-type(3) {
        background-color: deepskyblue;
      }
      .container div:nth-of-type(4) {
        background-color: salmon;
      }
      .container div:nth-of-type(5) {
        background-color: purple;
      }
      .container div:nth-of-type(6) {
        background-color: yellowgreen;
      }
      
    <div class="container">
      <div>
        <img src="./mask.png" alt="" />
      </div>
      <div>2</div>
      <div>3</div>
      <div>4</div>
      <div>5</div>
      <div>6</div>
    </div>
  • grid-template-columns: 100px 100px 100px;表示第一列、第二列、第三列的宽度
  • grid-template-rows: 50px 50px;表示第一行、第二行的高度

效果:

image.png

三、网格响应式

1、grid-template-columns: 1fr 2fr 1fr;

效果:

动图.gif fr控制宽度的比例

2、repeat函数

        grid-template-columns: repeat(3, 100px);
        grid-template-rows: repeat(5, 50px);

相当于

        grid-template-columns: 100px 100px 100px;
        grid-template-rows: 50px 50px;

3、auto-fit

        grid-template-columns: repeat(auto-fit, 100px);

auto-fit可以使布局列数成了自适应数量,但是宽度写死100px,右边有很大概率会有留白

动图.gif

4、minmax

        grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));

最小宽度为100px,若果有多余的宽度,均匀分配给每一列 动图.gif