Ric*_*ich 2 html css html-lists
我想布局一个定义列表,<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
Run Code Online (Sandbox Code Playgroud)
我得到的最接近的是使用 flexbox 并排放置元素,然后手动调整<dd>附加到长<dt>元素的元素的位置:
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
Run Code Online (Sandbox Code Playgroud)
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;
} Run Code Online (Sandbox Code Playgroud)
我可以想到其他几个解决方案,但如果不手动为较长的<dt>元素做一些事情,没有一个可以干净地工作。
我怎样才能在CSS中实现这种布局?我很乐意更改 HTML,只要它具有合理的语义即可。
这是一个不使用 flex 而是浮动的解决方案clear-both,对于min-widthsdt和calc(100% - [min-width of dt])s width:dd
dt {
min-width: 5em;
white-space: nowrap;
clear: both;
float: left;
}
dd {
margin: 0;
width: calc(100% - 5em);
float: right;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
225 次 |
| 最近记录: |