Lucian Davidescu Lucian Davidescu - 2 months ago 9
HTML Question

CSS floating dt/dd left in pairs

I have the following html code:

<dl>
<dt>term1</dt><dd>defn1</dd>
<dt>term2</dt><dd>defn2</dd>
<dt>term3</dt><dd>defn3</dd>
</dl>


I'm trying to have them floated in pairs (same width), with all the
dt
s going on the first line and all the
dd
s on the second one.

Like this:

term1 term2 term3
defn1 defn2 defn3


I have tried all sorts of combinations of display: block (+floats/clears), inline-block, table-*, flex, but none came any close.

Any idea how it could be done?

Answer

Here's one using flex box with no changes to your list, just CSS. Basically just defining the order of the children of dl using the nth-child pseudo selector. The calc() method used here is unfortunately dependent upon knowing the number of children in your list (in my example: 4).

With just CSS you can't really determine the number of children, but you can count siblings and prepare your CSS for different situations if you know the maximum number of items in your list:

Can CSS detect the number of children an element has?

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

dt,dd {
  margin: 0;
  flex-grow: 1;
  }

dt {
  order: 0;
  flex-basis: calc(100%/4);
}

dd {
  order: 1;
  flex-basis: calc(100%/4);
}
<dl>
  <dt>term1</dt><dd>defn1</dd>
  <dt>term2</dt><dd>defn2</dd>
  <dt>term3</dt><dd>defn3</dd>
  <dt>term4</dt><dd>defn4</dd>
</dl>

Comments