首页 > 解决方案 > 如何展平嵌套的 div 以在 CSS 网格中显示它们?

问题描述

我从一个应该是两列宽的对象生成一个表(使用 vue.js)。每一列都来自对象的键和值。这等效于以下实际 HTML:

<div id="table">
  <div>
    <div>
      this is something long on the first row
    </div>
    <div>
      short 1st row
    </div>
  </div>
  <div>
    <div>
      wazaa 2nd row
    </div>
    <div>
      wazii 2nd row
    </div>
  </div>
</div>

我使用 CSS 网格将它们格式化div为 2x2 网格,我希望它是

this is something long on the first row | short 1st row
wazaa 2nd row                           | wazii 2nd row

执行此操作的代码:

#table {
  display: grid;
  grid-template-columns: auto 1fr;
}
<div id="table">
  <div>
    <div>
      this is something long on the first row
    </div>
    <div>
      short 1st row
    </div>
  </div>
  <div>
    <div>
      wazaa 2nd row
    </div>
    <div>
      wazii 2nd row
    </div>
  </div>
</div>

结果不是我所期望的:两个最深的div行为就像它们应该在grid显示器之外一样:它们堆叠在一起。

我希望他们继承网格行为:根据列模板进行对齐。如何做到这一点?

标签: htmlcsscss-grid

解决方案


您可以使用display:contentshttps://caniuse.com/#feat=css-display-contents)来克服这个问题:

#table {
  display: grid;
  grid-template-columns: auto 1fr;
  grid-gap:10px;
}

#table > div {
  display:contents;
}
<div id="table">
  <div>
    <div>
      this is something long on the first row
    </div>
    <div>
      short 1st row
    </div>
  </div>
  <div>
    <div>
      wazaa 2nd row
    </div>
    <div>
      wazii 2nd row
    </div>
  </div>
</div>

或使用如下显示表:

#table {
  display: table;
}

#table > div {
  display:table-row;
}
#table > div > div {
  display:table-cell;
  padding:5px;
}
#table > div > div:first-child {
  white-space:nowrap;
  width:10%;
}
<div id="table">
  <div>
    <div>
      this is something long on the first row
    </div>
    <div>
      short 1st row
    </div>
  </div>
  <div>
    <div>
      wazaa 2nd row
    </div>
    <div>
      wazii 2nd row
    </div>
  </div>
</div>


推荐阅读