我有一个表格,单元格内有两个 div。我希望第一个 div 与单元格顶部对齐,最后一个 div 与底部对齐。这是表格的示例:
<table>
<tr>
<td class="left-cell">
<div class="cell-container">
<div class="first-div">
This content should be at top of the cell, but not overlap
</div>
<div class="last-div">
This content should be at bottom of the cell, but not overlap
</div>
</div>
</td>
<td>
Long Content
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
</td>
</tr>
<tr>
<td class="left-cell">
<div class="cell-container">
<div class="first-div">
This content should be at top of the cell, but not overlap
</div>
<div class="last-div">
This content should be at bottom of the cell, but not overlap
</div>
</div>
</td>
<td>
Shorter Content
</td>
</tr>
</table>
我的第一次尝试是在表格单元格上使用相对定位,在底部 div 上使用绝对定位。当表格单元格足够高以容纳所有内容时,此方法有效,但绝对定位会导致两个 div 对于较小的单元格重叠。
CodePen:https://codepen.io/Adam-Petersen/pen/mdgJwaG
接下来我尝试使用 Flexbox,但在表格单元格内使用 Flexbox 时似乎存在一些不平凡的渲染逻辑。这是迄今为止我想到的最好的尝试:
CodePen:https://codepen.io/Adam-Petersen/pen/NWmqgeZ
这在 Chrome 中完美运行,但在 Firefox 中不起作用。我不明白为什么
height: 0px
上需要 td
才能真正证明我在 Chrome 中想要的内容,但如果不使用 Firefox,我将不得不想出其他东西。
是否有某种方法可以使此 CSS 与 Firefox 兼容,或者是否有另一种完全我没有考虑的方法?
以防万一您没有陷入表格标记,您可以使用具有更灵活样式功能的网格。
.table-container {
height: 100vh;
display: grid;
grid-template-rows: 1fr;
}
.table-container>* {
padding: 1em;
}
.row-thing {
display: grid;
grid-template-columns: auto 1fr;
grid-template-rows: 1fr;
border: solid red 1px;
padding: 0.25em;
}
.left-cell {
padding: 1em;
background-color: #00ffff10;
}
.cell-container {
height: 100%;
display: grid;
grid-template-rows: 1fr auto;
align-items: space-between;
border: solid 1px blue;
}
.first-div {
align-self: start;
}
.last-div {
align-self: end;
}
<div class="table-container">
<div class="row-thing">
<div class="left-cell">
<div class="cell-container">
<div class="first-div">
This content should be at top of the cell, but not overlap
</div>
<div class="last-div">
This content should be at bottom of the cell, but not overlap
</div>
</div>
</div>
<div>
Long Content
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
</div>
</div>
<div class="row-thing">
<div class="left-cell">
<div class="cell-container">
<div class="first-div">
This content should be at top of the cell, but not overlap
</div>
<div class="last-div">
This content should be at bottom of the cell, but not overlap
</div>
</div>
</div>
<div>
Shorter Content
</div>
</div>
</div>