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:
-
text-overflow
: describes how hidden content should be shown to the user. -
white-space
: sets how white space inside an element is handled. -
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. -
width
: width of the content.
div {
width: 100%;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
}
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. - Finally
text-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>
Both examples in codepen
Ellipsis in input element:
Just use text-overflow: ellipsis
directly.
input {
text-overflow: ellipsis;
}
Happy coding!
Thanks for reading!
Top comments (4)
So how does the user read the truncated strings If wishes to do so
Use a
title
attribute on thediv
like example below:Now if user hover over
div tag
it will show the whole text in something like tooltip.Happy coding!
Thank you
Very useful! At my last company, we used to wrap half the page in these because long text was everywhere..