Search code examples
htmlcssword-wrap

How can I make 'dl' content word wrap the way a table 'td' would wrap?


I'm trying to get away from using tables for formatting whenever possible.

In a table, if a cell in my second column needs to wrap it will only wrap within that cell. When I try to use a list (dl) the 'second column' (dd) wraps under the entire line.

dt {
  display: block;
  float: left;
  text-align: right;
  color: black;
  width: 150px;
}

dt::after {
  content: ":";
  padding-left: .5em;
  padding-right: .5em;
}

dd {
  display: block;
  color: blue;
}
<dl>
  <dt>System Type</dt>
  <dd>My System Type</dd>
  <dt>Manufacturer</dt>
  <dd>Very very very very very long second column</dd>
</dl>

Screenshot of output:

(I'm not allowed to embed images yet)


Solution

  • I think you'll have to hard-code the width of the first column, it's the only way I was able to make any progress, but I think this is what you're looking for. Full credit where it's due, I was inspired by this answer which used percentages. It turns out better in this scenario if you hard-code the width with pixels instead, so you don't end up with a growing/shrinking gap between your "columns" like you would with percentages.

    You'll have to tweak the 120px value to suit your needs, it's what looked best with the two provided values.

    * {
        margin: 0;
    }
    dl {
        width: 100%;
    }
    dt {
        float: left;
        text-align: right;
        /* Hard code the width of the first column here */
        width: 120px;
    }
    dt::after {
        content: ":";
        padding-left: .5em;
        padding-right: .5em;
    }
    dd {
        float: left;
        /* Hard code the width of the 2nd column here...
           ... make it take up all the remaining space of the parent
        */
        width: calc(100% - 120px);
    }
    <dl>
        <dt>System Type</dt><dd>My System Type</dd>
        <dt>Manufacturer</dt><dd>Very very very very very long second column Very very very very very long second column Very very very very very long second column Very very very very very long second column Very very very very very long second column</dd>
    </dl>