htmlcsstext-aligndd

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>

Solution

  • 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