Recently, I met such a question in the interview. I found that I had neglected to organize the knowledge of CSS for a long time. Today, I will organize it. To keep the code simple, we implement a four-grid instead of a nine-grid

Implement quadrangle, child element width ADAPTS parent element width, spacing 10px

The implementation methods are as follows:

  • Flex
  • Grid
  • Table
  • Float TODO

Flex

Since Flex is a one-dimensional layout of elements, a div element is used to separate the child elements into different lines, and the child elements use flex-grow to implement adaptive widths

1. Row is used to separate rows

<div class="container">
  <div class='row'>
    <div class="item">1</div>
    <div class="item">2</div>
  </div>
  <div class='row'>
    <div class="item">3</div>
    <div class="item">4</div>
  </div>
</div>
<style type="text/css">
    .container { }
    .row {
      display: flex;
      margin: 10px 0;
    }
    .item {
      margin: 0 10px;
      background: red;
      flex-grow: 1;
    }
    .item:last-child {
      margin-left: 0;
    }
</style>
Copy the code

2. No row to separate lines

<div class="container">
    <div class="item">1</div>
    <div class="item">2</div>
    <div class="item">3</div>
    <div class="item">4</div>
</div>
<style type="text/css"> .container { display: flex; flex-wrap: wrap; } .item { background: red; // width: calc(100/3); // method 2 flex-basis: calc(100% / 3); } </style>Copy the code

Grid

The Grid is built for this two-dimensional layout, with FR units similar to flex-grow for adaptive implementation

 <div class="container">
    <div class="item">1</div>
    <div class="item">2</div>
    <div class="item">3</div>
    <div class="item">4</div>
</div>
<style type="text/css">
   .container {
      display: grid;
      grid-template-columns: 1fr 1fr;
      grid-template-rows: 1fr 1fr;
      grid-gap: 10px;
      padding: 10px;
   }
   .item {
      background: red;
   }
</style>
Copy the code

Table

I find the table layout very useful, and width adaptation can also be achieved with table.

<div class="container">
  <div class="row">
    <div class="item">1</div>
    <div class="item">2</div>
  </div>
  <div class="row">
    <div class="item">3</div>
    <div class="item">4</div>
  </div>       
</div>
<style type="text/css">
   .container {
      display: table;
      width: 100%;
      border-spacing: 10px;
   }
   .row {
      display: table-row;
   }
   .item {
      background: red;
      display: table-cell;
   }
</style>
Copy the code