html - 如何并排放置 <dt> 和 <dd> 的定义列表,但如果 <dt> 变长,则 <dd> 会向下移动?

标签 html css html-lists

我想列出一个定义列表<dl><dt>一列中的元素及其对应的 <dd>另一个元素。

棘手的部分是我想要我的 <dt> s 永远不会换行,如果它们对于第一列来说太宽,我想要 <dd>元素向下移动以腾出空间:

这是我的目标的屏幕截图:

the desired result, as described above

这是 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-bothmin-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/

相关文章:

css - CSS伪元素:before in multiple classes of same element的使用方法

Javascript 处理第二个按钮而不是第一个

css - 将 border-bottom 添加到 ol 中的 li

CSS - 无序列表中元素符号之间的垂直线

php - 为每个 WordPress 页面自定义背景图片?

javascript - ng-bind-html 工作,但抛出错误

html - 如何在移动 View 中以不同的顺序渲染 HTML 元素?

html - 制作HTML嵌套列表的正确方法?

Python 3.2 使用 urllib 从 HTML 代码中删除换行符

html - Outlook 上的按钮行高问题