Multiple Elements and CSS text overflow / ellipsis

Viewed 1850

Assume the following:

<li>
   <strong>Name:</strong>
   <span>John Doe</span>
</li>

The label part (the string in the <strong> tag) and the value part (the string in the <span> tag) can have any length. So, sometimes the label might be long and the value might be short, or vice versa, or both short, or both long.

When the combined width of the label and value exceeds a specified width, I'd like the tail-end of the concatenated string to display ellipsis. How do I do this in CSS?

UPDATE: what if the markup looked like this?

<dl>
   <dd>Name:</dd>
   <dt>John Doe</dt>
</dl>
3 Answers

You should use the following:

li {
    white-space: nowrap; 
    width: <your width> 
    overflow: hidden;
    text-overflow: ellipsis; 
}

Just set text-overflow: ellipsis on the containing <li> element.

li {
    overflow: hidden;
    text-overflow: ellipsis; 
    white-space: nowrap;
}
<ul>
  <li>
     <strong>Name:</strong>
     <span>John Doe John Doe John Doe John Doe John Doe John Doe John Doe John Doe John Doe John Doe John Doe</span>
  </li>

  <li>
     <strong>Very long long long long long long long long long long long long Name:</strong>
     <span>John Doe</span>
  </li>
</ul>

When working with a definition list, you can enclose <dt> and <dd> elements into a <div> (this is explicitly allowed by the spec since HTML5, but it works in a few older browsers, too). In this case, remember to style them with display: inline to display them in the same line of text.

dl>div {
    overflow: hidden;
    text-overflow: ellipsis; 
    white-space: nowrap;
}

dl>div>* {
    display: inline;
}
<dl>
  <div>
     <dd>Name:</dd>
     <dt>John Doe John Doe John Doe John Doe John Doe John Doe John Doe John Doe John Doe John Doe John Doe</dt>
  </div>

  <div>
     <dd>Very long long long long long long long long long long long long Name:</dd>
     <dt>John Doe</dt>
  </div>
</dl>

you can use this for li

li strong, li  span{
  width: 250px; /*change the width according to your choice */
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: inline;
  clear: both;
}

and for dl

dl dd, dl dt{
  width: 100px; /*change the width according to your choice */
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: inline;
  clear: both;
}
Related