dabadaba
dabadaba

Reputation: 9532

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.

Upvotes: 0

Views: 4078

Answers (2)

Peyman Mohamadpour
Peyman Mohamadpour

Reputation: 17964

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>

Upvotes: 3

Andy Tschiersch
Andy Tschiersch

Reputation: 3815

Something like this?:

.main-container {
  font-family: Calibri, serf;
  width: 350px;
  padding: 10px;
  border: 1px solid #ccc;
}
.main {
  border-top: 2px solid #ccc;
  margin-top: 10px;
  padding-top: 10px;
}
.extra-information {
  display: block;
  box-sizing: border-box;
  width: inherit;
  max-width: inherit;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}
<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>

Just added overflow: hidden;.

Upvotes: 0

Related Questions