Create a Table with CSS grid

南笙酒味 提交于 2019-12-01 07:20:34

In your first example, your data cells are children of the container. Hence, grid properties – which only work between parent and child – work as you expect.

In your second example, you have some data cells that are children of .row containers. These cells are no longer children of .wrapper, the grid container. Therefore, these cells are outside the scope of grid layout, do not recognize grid properties and are rendered as standard block-level elements.

So, basically, grid containers with different child elements render different layouts.

One solution to get your examples to match would be to make the grid items into grid containers having the same properties as the parent. Here's the general idea:

Revised Codepen

.wrapper {
  display: grid;
  grid-template-columns: repeat(3, minmax(50px, 1fr));
  background-color: #fff;
  color: #444;
  max-width: 800px;
}

.row {
  grid-column: 1 / -1;
  display: grid;
  grid-template-columns: repeat(3, minmax(50px, 1fr));
}

div:nth-child(4) { grid-row-start: 2; }
div:nth-child(5) { grid-row-start: 3; }

.box {
  background-color: #444;
  color: #fff;
  border-radius: 5px;
  padding: 20px;
  font-size: 150%;
}
<div class="wrapper">
  <div class="box a">col 1</div>
  <div class="box b">col 2</div>
  <div class="box c">col 3</div>

  <!-- Table Row -->
  <div class="row">
    <div class="box d">short data</div>
    <div class="box e">a really long piece of data</div>
    <div class="box f">short data</div>
  </div>

  <!-- Table Row -->
  <div class="row">
    <div class="box d">short data</div>
    <div class="box e">a really long piece of data</div>
    <div class="box f">short data</div>
  </div>
</div>
Matveev Dmitriy

display: contents is what you need.

contents

These elements don't produce a specific box by themselves. They are replaced by their pseudo-box and their child boxes.

Add this CSS (example):

.row {
    display: contents;
}

More links:

It didn't break, it works exactly as intended. Every child element is using one cell of the grid, if you wrap your header in another div you'll see they swap rows for columns, because each group will use one cell.

If you are going to display tabular data, then you should stick with tables as they are the semantically correct element for that purpose.

However if you are trying to build responsive designs or you really want to use grid I suggest you to read this incredible article about CSS grids.

Take a look in display: subgrid; maybe it is what you are looking for in this scenario.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!