在纯 CSS 中折叠 table-row 的高度(不影响 table 宽度)

Collapse table-row's height in pure CSS (without affecting the table width)

我有以下 HTML 的片段,其中有效的 table 用于对齐形式:

<div id="one">
  <p>
    <label for="a">a</label> <input type="text" id="a">
  </p>
  <p class="h">
    <label for="b">bbbbbb</label> <input type="text" id="b">
  </p>
</div>

与以下 CSS:

#one {
  display: table;
  width: auto;
}

p {
  display: table-row;
}

p label, p input {
  display: table-cell;
}

#one 是自动计算宽度的东西,labels 和 inputs 是未知宽度。我想要对齐形式的功能,但是这样添加 class h 到他们的行然后删除,使其他元素垂直 space,但不改变 #one 的宽度,因为它应该位于自动计算宽度的其他元素旁边。

CSS3 中的 .h 定义会让我的 "table row" (p) 高度等于 0 或以其他方式直观地删除它而不改变其宽度parent?如果需要,我可以更改 HTML,但我想找到一个不使用 JS 的解决方案。

visibility: hidden不垂直去掉,height: 0不行(可能是因为是table-row),display: none不行,因为改变了有效宽度为 0。我希望我的 #one 保持相同的宽度。将 display: block !importantheight: 0 结合使用部分有效,但会留下一个奇怪的垂直 space(并且 block 不应该是 table 的 child ).

我正在搜索的内容与 this SO question 类似,但我正在搜索一个纯粹的 CSS 解决方案并且没有固定 table 宽度。

您可以在这里玩:JSFiddle

好的,这可能是您的解决方案。请注意,它不一定是 flex - 它也适用于浮点数,但不适用于 display: table (老实说,我真的不明白在 2018 年使用它的意义) .

顺便说一句,我在 .h 之后又添加了一个 "row" 以便我们可以控制发生的事情。如果一切正常,我们应该看到 .h 垂直 "collapsing" 以便第一行和第三行接触。

#one {
  display: inline-block;
  background-color: #F0FFFF;
}

p {
  display: flex;
  justify-content: space-between;
  margin: 0; /* this is crucial because paragraphs have some margin set by default and I cannot know do you "reset" or "normalize" your css */
}

.h {
  transform: scaleY(0); /* this is something that is used actually quite often for animating dropdown menus */
  transform-origin: 50% 0; /* this line of code isn't contributing anythow NOW to your problem, but should you choose to animate "collapsing" the height of the row, it is setting its origin of transformation to the middle of the top border */
  height: 0;
}
<div id="one">
  <p>
    <label for="a">a</label> <input type="text" id="a">
  </p>
  <p class="h">
    <label for="b">bbbbbb</label> <input type="text" id="b">
  </p>
  <p>
    <label for="a">a</label> <input type="text" id="a">
  </p>
</div>

此外,您可以根据需要添加 visibility: hidden,但这不会改变解决方案。希望对您有所帮助。

编辑:

在寻找解决方案的过程中,我偶然发现了这篇文章(尤其是 - this part)。尽管这篇文章建议 visibility: collapse 几乎不应该被使用,但我觉得值得一提,因为它回答了您最初的问题。而且,老实说,我刚刚在研究时了解到 "feature" 的可见性。可能是因为从来没有人使用过它 :D.

CSS 对于您的 原始 代码将只添加一条规则(但您也可以将其与 scaleY、height... 结合使用):

#one {
  display: table;
  width: auto;
}

p {
  display: table-row;
}

p label, p input {
  display: table-cell;
}

.h {
  visibility: collapse;
}

延伸阅读: MDN: Visibility

(visibility: collapse) For rows, columns, column groups, and row groups, the row(s) or column(s) are hidden and the space they would have occupied is removed (as if display: none were applied to the column/row of the table). However, the size of other rows and columns is still calculated as though the cells in the collapsed row(s) or column(s) are present. This value allows for the fast removal of a row or column from a table without forcing the recalculation of widths and heights for the entire table.