DEV Community

Cover image for Truncate string with ellipsis
Rohit Kumawat
Rohit Kumawat

Posted on • Updated on

Truncate string with ellipsis

Sometimes we required to adjust long strings in one line and show ellipsis(...) at the end of the string as a symbol that this text is long.

Then we can use the title attribute to show the full string on the hover of text.

To truncate long strings we will use the following CSS properties:

  1. text-overflow: describes how hidden content should be shown to the user.
  2. white-space: sets how white space inside an element is handled.
  3. overflow: property specifies whether to clip the content or to add scrollbars when the content of an element is too big to fit in the specified area.
  4. width: width of the content.
div {
  width: 100%;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}
Enter fullscreen mode Exit fullscreen mode

text-overflow property is used with white-space and overflow to show this ellipsis signal if the content is clipped.

  • white-space: nowrap: text will not be wrapped.
  • overflow: hidden: hide/clip the content in fix width.
  • Finallytext-overflow: ellipsis: will show the sign (...) stating that this text is clipped.

Inform user about full-text content:

  • For that use the title attribute.
  • If used, the long string will be shown to the user if hovered on div like the example below.
const longText = Hey everyone, This code shows how we can truncate long strings so that they can show as an ellipsis. we can use 100% width to adjust the text in one line.

<div title={longText}>{longText}</div>
Enter fullscreen mode Exit fullscreen mode

Both examples in codepen

Ellipsis in input element:

Just use text-overflow: ellipsis directly.

input {
  text-overflow: ellipsis;
}
Enter fullscreen mode Exit fullscreen mode

Happy coding!

Thanks for reading!

Top comments (4)

Collapse
 
ademola_isr profile image
ADEMOLA OGUNMOKUN

So how does the user read the truncated strings If wishes to do so

Collapse
 
ip127001 profile image
Rohit Kumawat • Edited

Use a title attribute on the div like example below:

const longText = "Hey everyone, This code shows how we can truncate long strings so that they can shown as ellipsis. we can use 100% width to adjust text in one line."

<div title={longText }>{longText }</div>

Now if user hover over div tag it will show the whole text in something like tooltip.

Happy coding!

Collapse
 
ademola_isr profile image
ADEMOLA OGUNMOKUN

Thank you

Collapse
 
abdisalan_js profile image
Abdisalan

Very useful! At my last company, we used to wrap half the page in these because long text was everywhere..