skip to Main Content

I am looking to create a list using dl, dt and dl that is going to work like label text: description value.

For example the final result I am looking for is the following:

ID: 345
Price: 234.023$

The dt (ID: and Price:) I like to have max-content width, while the dd (345 and 234.023$) I want to occupy the rest of the line width

The HTML producing this output I want to be the following:

<dl>
    <dt>ID:</dt>
    <dd>345</dd>
    <dt>Price:</dt>
    <dd>234.023$</dd>
</dl>

What I need, is the dt to have max-content width and the dd occupy the remaining space before the flex wrap to a new line for the next dt.

My current CSS code is the following:

dl {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

dt {
    flex: 0 0 max-content;
    font-weight: bold;
}

dd {
    flex-grow: 1;
}

But unfortunately this code doesn’t work as expected. Can someone more experienced with the flex box module help me achieve that goal? (if possible ofcourse)

My current code result is here:

dl {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

dt {
    flex: 0 0 max-content;
    font-weight: bold;
}

dd {
    flex-grow: 1;
}
<dl>
    <dt>ID:</dt>
    <dd>345</dd>
    <dt>Price:</dt>
    <dd>234.023$</dd>
</dl>

2

Answers


  1. If you want to keep your HTML structure the way it currently is, here is a simple solution that actually uses CSS grid instead of Flexbox.

    Using grid-template-columns, you can set two columns. The first column can have width max-content, and the second can have width 1fr (which will make the second column fill up the remaining space). With this, every pair of <dt> and <dd> will be placed in its own 2-column row with those column widths.

    dl {
        display: grid;
        grid-template-columns: max-content 1fr;
        gap: 10px;
    }
    
    dt {
        font-weight: bold;
    }
    
    dd {
    }
    <dl>
        <dt>ID:</dt>
        <dd>345</dd>
        <dt>Price:</dt>
        <dd>234.023$</dd>
    </dl>
    Login or Signup to reply.
  2. Use float, yes float.

    dt {
      float: left;
      clear: left;
      font-weight: bold;
      margin-right: 10px;
    }
    
    dd {
      display: block;
      margin: 0 0 10px;
    }
    <dl>
      <dt>ID:</dt>
      <dd>345</dd>
      <dt>Price:</dt>
      <dd>234.023$</dd>
    </dl>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search