html - 如何展平嵌套的 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
显示器之外一样:它们堆叠在一起。
我希望他们继承网格行为:根据列模板进行对齐。如何做到这一点?
解决方案
您可以使用display:contents
(https://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>
推荐阅读
- mysql - Laravel:有一个现有的查询,但只需将其应用于过去 30 天
- django - PasswordResetDoneView 未在 Django 中使用自定义模板
- c++ - 为什么这仍然执行甚至设置为 nullptr
- roxygen2 - 如何格式化类似于参数列表的 roxygen2 返回列表?
- java - 是否可以使用jsp登录表单作为spring security的自定义登录表单
- python - 使用 json 从节点到 python 的通信给了我错误
- java - Java、Maven、JSP、JPA - java.lang.NumberFormatException:对于输入字符串:“id”
- c# - 为什么在 .NET 方法注释中使用数字字符引用?
- c - PIE 文件在链接期间是否提供了虚拟内存地址?
- json - 根据 JSON 标准对某些 tableView 行应用复选标记