css 为什么相同宽度的表格行与网格之间存在差异?

k4ymrczo  于 2023-05-08  发布在  其他
关注(0)|答案(2)|浏览(194)

我有一个HTML表,它的子表显示table-rowtable-cell。其中的一些行被设置为网格样式,以便更好地定位其中的元素。这导致端部定位的元素的少量偏移,因为行的宽度变得不均匀。
如何缓解这种行为并保持网格设置?

table {
  border-collapse: collapse;
  width: 400px;
}
tr {
  border: 5px solid orange;
}
td {
  height: 50px;
}
tr.grid {
  border-color: green;
  display: grid;
}
<table>
  <tr>
    <td></td>
  </tr>
  <tr class="grid">
    <td></td>
  </tr>
</table>
lmvvr0a8

lmvvr0a81#

这会发生在您给予<tr>的每个显示器上。奇怪的是,table就是这样工作的。一种解决方法是向.grid类添加一些css

tr.grid {
  width: calc(100% - 5px);
  margin-left: -3px;
}

这至少修复了代码片段,但可能因项目本身而异。

mbjcgjjk

mbjcgjjk2#

我建议将标记更改为一组div和span,并使用CSS来显示“table”。当你不想让表格使用默认的样式和标记时,表格的样式总是很“有趣”。

body {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

table-container {
  display: table;
  border-collapse: collapse;
  width: 400px;
}

.table-row {
  border: 5px solid orange;
}

.table-row.grid {
  border-color: green;
  display: grid;
  grid-auto-flow: column;
  grid-template-rows: 50px;
}

.table-row span {
  display: inline-block;
  border: solid 1px blue;
}
<div class="table-container">
  <div class="table-row">
    <span>&nbsp;</span><span>&nbsp;</span><span>&nbsp;</span>
  </div>
  <div class="table-row grid">
    <span>&nbsp;</span><span>&nbsp;</span><span>&nbsp;</span>
  </div>
</div>

相关问题