【问题标题】:How do I style dd and dt elements to be on the same line with dt right aligned and dd left aligned?如何将 dd 和 dt 元素设置在同一行,dt 右对齐和 dd 左对齐?
【发布时间】:2020-09-06 01:40:58
【问题描述】:

我有一个键值对的定义列表,我想将它们放在同一行并对齐它们的文本,以便 dt 元素右对齐,dd 元素左对齐。我还想在两者之间添加一个 : ,全部通过 CSS。我已经看到了如何通过使用 float:left 将它们放在同一行上的示例,但是一旦我添加了 text-align ,它们就会回到不同的行上。我不需要使用该方法,但我对 CSS 不够熟悉,不知道如何设置样式以获得所需的结果。有谁知道我该怎么做?

这是我的 HTML 代码:

  <dl>
    <dt>Username</dt> <dd>Username02</dd>
    <dt>Password</dt> <dd>p1HvkNAAx6P</dd>
    <dt>Security Question</dt> <dd>What is your pets name?</dd>
    <dt>Security Answer</dt> <dd>Fred</dd>
    <dt>Security Question</dt> <dd>What is your favorite color?</dd>
    <dt>Security Answer</dt> <dd>Blue</dd>
  </dl>

【问题讨论】:

  • 您可以使用 flexbox,但是如果您正在寻找可行的解决方案,我建议您至少发布您的 HTML 代码。
  • 谢谢,这是个好建议。我已经添加了。

标签: html css dt text-align dd


【解决方案1】:

这应该会给你一个很好的印象:

dl {
  display: flex;
  flex-wrap: wrap;
}

dt,
dd {
  box-sizing: border-box;
  width: 50%;
  margin: 0;
}

dt:nth-of-type(2n),
dd:nth-of-type(2n) {
  margin-bottom: 1em;
}

dt {
  text-align: right;
  padding-right: 10px;
}

dd {
  padding-left: 10px;
}

dt:after {
  content: ":";
}

这里的工作示例:https://codesandbox.io/s/small-bash-qgw43?file=/index.html:255-684

【讨论】:

    【解决方案2】:

    你可以使用这个 CSS 来获得想要的结果

    dt,
    dd {
      display: inline-block;
      width: calc(50% - 0.5rem);
      margin: 0;
    }
    
    dt {
      text-align: right;
    }
    
    dt::after {
      content: ":";
    }
    

    Example Code

    【讨论】:

      猜你喜欢
      • 2016-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-07
      • 1970-01-01
      • 2010-12-15
      • 2016-09-05
      • 2023-03-31
      相关资源
      最近更新 更多