英文:
React - Fluent UI - How to truncate the text in a card
问题
我有来自这个链接的示例:https://codesandbox.io/s/upbeat-wood-tscc2h?file=/example.tsx
如果卡片中的文本太长,文本会被截断。我一直在尝试截断文本,以便在末尾使用省略号或类似的东西,以使文本看起来不那么难看,但我一直没有找到解决方案。
这是否可能?
英文:
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?
答案1
得分: 3
要截断文本并在文本溢出其容器时显示省略号(三个点 ...
),您可以使用一组CSS样式组合:
white-space: nowrap
以防止文本换行。overflowX: hidden
以隐藏块级元素左右边缘的溢出文本。overflowY: hidden
以隐藏块级元素顶部和底部边缘的溢出文本。text-overflow: ellipsis
以在文本溢出其框时显示省略号。
(我尝试使用 overflow,但它一直报错:overflow: string Type 'string' is not assignable to type 'never'.ts(2322)
)
但是,要使这些样式起作用,容器需要具有定义的宽度,不能无限增长。
为截断文本添加一个新样式。
truncatedText: {
whiteSpace: "nowrap",
overflowX: "hidden",
overflowY: "hidden",
textOverflow: "ellipsis",
maxWidth: "100%"
},
将 truncatedText
样式应用于您想要截断的文本;更新包含长文本的 <p>
:
<p className={`${styles.text} ${styles.truncatedText}`}>
Donut chocolate bar oat cake. Dragée ...
// 其余文本
</p>
请参阅 codesandbox.io
通过这些更改,如果卡片中的文本变得过长以适应其容器,它将被截断,并显示省略号。
注意:这仅在文本预计适合一行时起作用。
英文:
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.
Note: That will work when the text is expected to fit on one line.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论