Stacy
Stacy

Reputation: 107

How do I style dd and dt elements to be on the same line with dt right aligned and dd left aligned?

I have a definition list of key value pairs, and I want to put them on the same line and align their text so that the dt elements are right aligned and the dd elements are left aligned. I also would like to add a : inbetween the two, all via CSS. I've seen examples of how to get them on the same line by using float: left, but once I add text-align they go back to being on different lines. I don't need to use that method, but I'm not familiar enough with CSS to know how to style this to get the desired result. Does anyone know how I could do this?

enter image description here

Here is my HTML Code:

  <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>

Upvotes: 2

Views: 1662

Answers (2)

This should give you a very good impression:

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: ":";
}

Working example here: https://codesandbox.io/s/small-bash-qgw43?file=/index.html:255-684

Upvotes: 1

Zain Zafar
Zain Zafar

Reputation: 936

You can use this CSS to get desired results

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

dt {
  text-align: right;
}

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

Example Code

Upvotes: 3

Related Questions