css - 如何让省略号显示在CSS中的文本上

标签 css

我正在尝试使用 CSS 在我的长文本上显示一个省略号。当文本不包含空格时,这似乎工作正常,因此不能被打破(即换行),但当它包含空格时,省略号不会出现。

我的代码是:

<!DOCTYPE html>
<html>
    <head>
        <style>
span {
    width: 150px;
    display: inline-block;
    border: 1px dotted blue;
    height: 1em;
    overflow: hidden;
    text-overflow: ellipsis;
    padding: 4px;
}       
        </style>
    </head>
    <body>
        <div>
            <span>
            This is some long text that I want to have an ellipsis on.
            </span>
        </div>
        <div>
            <span>
            afejaklfjefklafjeklfjeklfjeklfejfklejfkfjeklfjeklfejfklaejfeklfejfklejfklfejfkl
            </span>
        </div>
    <body>
</html>

Here's my fiddle.

最佳答案

如果您添加 white-space:nowrap 省略号将会出现。原因是您的带空格的文本会在有空格的情况下换行,并且不需要省略号。如果您删除 overflow-hidden 并且文本将被换行显示,您可以看到它的实际效果。

span {
    width: 150px;
    display: inline-block;
    border: 1px dotted blue;
    height: 1em;
    overflow: hidden;
    text-overflow: ellipsis;
    padding: 4px;
    white-space: nowrap;
}       

来自 doc

The text-overflow declaration allows you to deal with clipped text: that is, text that does not fit into its box. text-overflow comes into play only when: the box has overflow other than visible (with overflow: visible the text simply flows out of the box) the box has white-space: nowrap or a similar method of constraining the way the text is laid out. (Without this, the text would wrap to the next line)

关于css - 如何让省略号显示在CSS中的文本上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16782691/

相关文章:

css - 有没有 Sass 代码格式化程序?

javascript - 我想上传文件并制作自定义输入文件,它在每个浏览器中都有效,但在 safari 中无效

html - 未能保持适当的位置(HTML/CSS)

css - 如何使 DIV (SIDEBAR) 延伸到滚动页面的末尾?

html - 在 Chrome 中进行 css 转换后,只有链接的右侧可点击

css - Chrome 浏览器中的自动宽度不起作用

css - 如何集中动态元素

html - table 不会收起来

php - 如何根据购物车中的产品数组或类别隐藏 DIV?

javascript - 许多文本区域无法正常工作 - JQuery