我如何将dd和dt元素设置为同一行,且dt右对齐和dd左对齐?

问题描述 投票:0回答:1

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

enter image description here

这是我的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>
html css dt text-align dd
1个回答
0
投票

您可以使用此CSS获得所需的结果

dt,
dd {
  display: inline-block;
  width: calc(50% - 0.5rem);
  margin: 0;
}

dt {
  text-align: right;
}

dt::after {
  content: ":";
}

Example Code


0
投票

这应该给您很好的印象:

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

© www.soinside.com 2019 - 2024. All rights reserved.