1

I have the example from this link: https://codesandbox.io/s/upbeat-wood-tscc2h?file=/example.tsx

If the text in the card is too long, the text is clipped. I've been trying to truncate the text so I have some sort of elipses or something similar at the end so the text doesn't look bad but I haven't been able to find a solution.

Is this possible?

user3587624
  • 1,427
  • 5
  • 29
  • 60

1 Answers1

3

To truncate the text and show ellipsis (three dots ...) when the text overflows its container, you can use a combination of CSS styles:

  • white-space: nowrap to prevent wrapping of the text.
  • overflowX: hidden to hide overflowing text for a block-level element's left and right edges.
  • overflowY: hidden to hide overflowing text for a block-level element's top and bottom edges.
  • text-overflow: ellipsis to show an ellipsis when the text overflows its box.

(I tried using overflow, but it kept erroring with: overflow: string Type 'string' is not assignable to type 'never'.ts(2322))

However, for these styles to work, the container needs to have a defined width and not be allowed to grow indefinitely.

Add a new style for the truncating text.

truncatedText: {
    whiteSpace: "nowrap",
    overflowX: "hidden",
    overflowY: "hidden",
    textOverflow: "ellipsis",
    maxWidth: "100%"
},

Apply the truncatedText style to the text you want to truncate; update the <p> containing the long text:

<p className={`${styles.text} ${styles.truncatedText}`}>
    Donut chocolate bar oat cake. Dragée ...
    // rest of the text
</p>

See codesandbox.io

With these changes, if the text in your card becomes too long for its container, it will be truncated and an ellipsis will be shown.

truncated text

Note: That will work when the text is expected to fit on one line.

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • Isn't it possible to do it to truncate after several lines? – user3587624 Aug 07 '23 at 22:04
  • 1
    @user3587624 I actually [just tested multiple lines](https://codesandbox.io/s/icy-thunder-gfclv9?file=%2Fexample.tsx), it seems to work (within one paragraph). – VonC Aug 07 '23 at 22:08