Three ways to implement a three-column CSS layout

Requirements describe

Three-column layout is very common in our life. It is generally required to have fixed width on both sides and adaptive width in the middle. For example:

Now let’s do it ourselves. Suppose we have the following HTML code that requires a three-column layout.

<div class="column-container">
  <div class="column left">left</div>
  <div class="column center">center</div>
  <div class="column right">right</div>
</div>
Copy the code

The results are as follows:

The easiest way is to use Flex or Grid. They are designed to deal with this kind of situation.

1. The grid

By setting the outermost layer to the Grid layout. Divide the content into three columns, with the width of the middle column being auto. If we need to set the spacing of each column, we can also use the column-gap property. The code is as follows:

.column-container {
  display: grid;
  grid-template-columns: 200px auto 200px;
  column-gap: 10px;
}
Copy the code

2. The flex implementation

Set the container layout to Flex and add flex: 1 to the middle column with the left and right width fixed as follows:

.column-container {
  display: flex;
  column-gap: 10px;
}
.left..right {
  width: 200px;
}
.center {
  flex: 1;
}
Copy the code

Flex also has an interesting property called Order, assuming the HTML code looks like this with center in the middle.

<div class="column-container">
  <div class="center">center</div>
  <div class="left">left</div>
  <div class="right">right</div>
</div>
Copy the code

You can sort the contents of Flex by setting the Order property.

.left {
  order: 0;
}
.center {
  order: 1;
}
.right {
  order: 2;
}
Copy the code

3. Traditional float layout

This method is no longer recommended for the following reasons:

  1. The code is not neat to implement
  2. Flexibility is also relatively low, add margin when trouble.
  3. Check the fit in the responsive section.

However, we can also compare with the previous two methods of Flex and Grid, and the results are as follows:

Code implementation:

.left {
  width: 200px;
  float: left;
}
.right {
  width: 200px;
  float: right;
}
.center {
  width: 100%;
}
Copy the code