我想列出一个定义列表<dl>
与 <dt>
一列中的元素及其对应的 <dd>
另一个元素。
棘手的部分是我想要我的 <dt>
s 永远不会换行,如果它们对于第一列来说太宽,我想要 <dd>
元素向下移动以腾出空间:
这是我的目标的屏幕截图:
这是 ASCII 艺术版本:
first dt first dd goes here and can be any length
second dt second dd is here and also any length
a much longer dt that overlaps
third dd moves down to make room
last dt last dd
我得到的最接近的是使用flexbox并排放置元素,然后手动调整 <dd>
的位置附加到 long <dt>
的元素元素:
dl {
display: flex;
flex-flow: row wrap;
}
dt {
flex-basis: 10em;
white-space: nowrap;
}
dd {
flex-basis: calc(100% - 10em);
margin: 0;
}
dt.long-dt {
flex-basis: 100%;
}
dt.long-dt + dd {
flex-basis: 100%;
padding-left: 10em;
}
<dl>
<dt>one</dt>
<dd>one</dd>
<dt class="long-dt">two that is longer</dt>
<dd>two only moves down because I manually told it to in the CSS</dd>
<dt>three</dt>
<dd>three</dd>
</dl>
我可以想到其他几个解决方案,但没有一个可以在不手动长时间执行操作的情况下干净地工作 <dt>
元素。
如何在 CSS 中实现这种布局?我很乐意更改 HTML,只要它具有合理的语义即可。
最佳答案
这里的解决方案不使用 Flex,而是使用 float 、clear-both
和 min-width
来表示 dt
和 calc(100% - [dt 的最小宽度])
用于 dd
的宽度
:
dt {
min-width: 5em;
white-space: nowrap;
clear: both;
float: left;
}
dd {
margin: 0;
width: calc(100% - 5em);
float: right;
}
<dl>
<dt>one</dt>
<dd>one</dd>
<dt>two that is longer</dt>
<dd>two moves down without having to manually tell it to in the CSS</dd>
<dt>three</dt>
<dd>three</dd>
<dt>four which is also longer</dt>
<dd>four dd which is even longer and has to wrap into two lines, at least on rather narrow screens or in narrow parent elements. It also moves down without having to manually tell it to in the CSS</dd>
<dt>five</dt>
<dd>five</dd>
</dl>
关于html - 如何并排放置 <dt> 和 <dd> 的定义列表,但如果 <dt> 变长,则 <dd> 会向下移动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75836294/