dabadaba dabadaba - 1 month ago 7
CSS Question

Adjust width to parent's width and truncate when higher

I have a panel with information and above it there's additional information displayed, but I'd like it to be subtle and a one-liner, so when the text that's contained in it is wider than the parent's width, it should be truncated.

See jsfiddle; this is a mock of what I am after.

This is the HTML for that extra information:

<div class="main-container">
<div class="extra-information">
<span>Information</span> –
<span>When this is too long it should be truncated</span>
</div>
<div class="main">Main panel</div>
</div>


And this is the CSS I am trying so far:

.main-container {
width: 350px;
// ...
}

.main {
// ...
}

.extra-information {
display: block;
box-sizing: border-box;
width: inherit;
max-width: inherit;
white-space: nowrap;
text-overflow: ellipsis;
}


Check it out in another jsfiddle.

Answer

You may use text-overflow: ellipsis with overflow: hidden in CSS


text-overflow

The text-overflow property specifies how overflowed content that is not displayed should be signaled to the user.

Other possible values for this property are:

  • clip : Default value. Clips the text
  • ellipsis : Render an ellipsis ("...") to represent clipped text
  • string : Render the given string to represent clipped text

overflow

The overflow property specifies what happens if content overflows an element's box.

This property specifies whether to clip content or to add scrollbars when an element's content is too big to fit in a specified area.

Note

The overflow property only works for block-level elements.

.main-container {
  width: 350px;
}

.extra-information {
    white-space: nowrap;
    overflow:hidden !important;
    text-overflow: ellipsis;
}
<div class="main-container">
  <div class="extra-information">
    <span>Information</span> –
    <span>When this is too long it should be truncated</span>
  </div>
  <div class="main">Main panel</div>
</div>