首页 > 解决方案 > CSS Flex:制作类似网格的布局最准确的方法是什么?

问题描述

按照设计,flex (最初)是一个单一的内容通道,并不是专门为网格制作的。

我目前使用flex-wrap: wrap;它,但它并不是真正用于制作网格 - 尽管它可能是您尝试制作的第一个选项。

此外,我认为这不是创建类似网格布局的唯一方法。

那么这是最准确(正确)的方式吗?在 flex 中创建网格?

还是有更好的选择?

编辑(在发布 2 个答案后):只是为了澄清,我不是在寻找display: grid;我在问什么是最合适/最准确的方式在 flex 中进行。(参见css 弹性网格

(当然display: grid是用 CSS 网格制作网格的正确方法。这不是问题要问的。)

标签: csslayoutflexboxgrid

解决方案


My advise is to go with display: grid.

To get started you have to define a container element as a grid with display: grid, set the column and row sizes with grid-template-columns and grid-template-rows, and then place its child elements into the grid with grid-column and grid-row.

This is an useful post about https://css-tricks.com/snippets/css/complete-guide-grid/

And this is a complete example:

The style:

.grid-container {
  display: grid;
  grid-template-columns: auto auto auto;
  background-color: red;
  padding: 1px;
}

.grid-item {
  background-color: rgba(255, 255, 255, 0.8);
  border: 1px solid #000;
  padding: 20px;
  font-size: 30px;
  text-align: center;
}

and the layout:

<div class="grid-container">
  <div class="grid-item">1</div>
  <div class="grid-item">2</div>
  <div class="grid-item">3</div> 
</div>

推荐阅读