Truncate string with ellipsis

ip127001

Rohit Kumawat

Posted on August 21, 2020

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!

💖 💪 🙅 🚩
ip127001
Rohit Kumawat

Posted on August 21, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Truncate string with ellipsis
css Truncate string with ellipsis

August 21, 2020