【发布时间】:2026-02-08 19:35:01
【问题描述】:
我想根据响应宽度截断单行文本,并在末尾添加“和更多”而不在单词中间中断。我拼凑了一个工作示例,但我无法让它与居中对齐的文本一起工作。
https://jsfiddle.net/p02147zd/2/
当一个框最后不需要“和更多”时,它会错位,因为它仍然具有为该文本留出空间所需的填充权。如果我左对齐文本看起来不错,但我需要它居中。有什么想法吗?
.foo {
padding-right: 58px; /* Always have room for "and more" */
height: 1.1em; /* Only allow one line of text */
overflow: hidden; /* Hide all the text below that line */
background-color: yellow;
}
.foo > span {
display: inline-block; /* These have to be inline block to wrap correctly */
position: relative; /* Give "and more" an anchor point so it's positioned after the element */
background-color: yellow; /* Cover "and more" of the previous element with the same background color */
white-space: pre; /* Make sure the only point where wrapping is allowed is before a comma */
}
.foo > span:after {
position: absolute; /* Take "and more" out of the flow, so the next item will cover it */
content: 'and more'; /* Each span has an "and more" */
margin-left:2px;
}
.foo > span:last-child:after {
content: ""; /* Except for the last one */
}
谢谢!
【问题讨论】:
标签: css truncate truncation