CSS溢出省略号仅在第一个元素上

3
我正在尝试让每一行都始终显示“位置(place)”。但是,当内容太长时,我希望标题上出现省略号。以下是目前我所拥有的代码:
<ul class="results">
   <li class="item"> <span class="title"><a href="item.html" target="_blank">The numbers in the table specify the first browser version that fully supports the property</a></span><span class="place">Place</span>
   </li>
</ul>

.item {
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap
}

http://jsfiddle.net/m6krvapf/5/

问题在于被截断的是行末,这意味着“位置”首先被切断。是否有可能始终保留该位置,并仅将省略号放在其左侧的内容上?


可能是Css文本溢出省略号不起作用的重复问题。 - dippas
3个回答

6
你可以像这样包裹你想要省略的部分:
<li class="item"> 
    <span class="ellipsis"><span class="title"><a href="item.html" target="_blank">The numbers in the table specify the first browser version that fully supports the property</a></span></span>
    <span class="place">Place</span>
</li>

然后使用以下样式:
.item {
    white-space: nowrap;
}
.ellipsis {
    text-overflow: ellipsis;
    overflow: hidden;
    display:inline-block;
    max-width:85%;
}

在屏幕较小的情况下,如果“Place”超过屏幕的15%(约230px),则可以使用以下媒体查询:

示例

@media all and (max-width: 230px) {
    .item {
        overflow:auto;
        padding-right: 3em;
    }

    .ellipsis {
        max-width:none;
        width:100%;
        float:left;
    }

    .place 
    {
        display:inline-block;
        width:3em;
        float:right; 
        margin-right:-3em;
    }
}

示例:

Example


嗨Pete。这个看起来完美运行,除了当我把窗口变小时,它会给我一个水平滚动条,而不是从文本中删除内容。也就是说,永远不应该有水平滚动条。我解释清楚了吗?:s - Jimmy
您可能需要在极小的屏幕上添加一个媒体查询来更改最大宽度。我会尝试一些方法并发表评论。 - Pete

2

您可以将span转换为块,使用CSS浮动并交换它们的位置,如此Fiddle所示,CSS代码如下:

.item span {
    display: block;
}
.title {
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap
}
.place {
    float: right;
}

对于这个HTML:

<ul class="results">
    <li class="item">
        <span class="place">Place</span>
        <span class="title"><a href="item.html" target="_blank">The numbers in the table specify the first browser version that fully supports the property</a></span>
    </li>
    <li class="item">
        <span class="place">Place</span>
        <span class="title"><a href="item.html" target="_blank">The numbers in the table specify the first browser version that fully supports the property</a></span>
    </li>
</ul>

这样,“Place”始终保持在右侧。另一种解决方案是使用原始的HTML,但将标签设置为块级元素,向左浮动并设置span.titlemax-width,就像这个示例中使用的CSS一样:

.item span {
    display: block;
    float: left;
    line-height: 1em;
}
.title {
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
    max-width: calc(100% - 50px);
}

非常好。那么,浮动(float)将给span元素提供"空白"或者说"宽度",只有这样我们才能够应用文本溢出属性,这是正确的解释吗? - Rishi
这是一个不错的解决方案,只是它将“位置”右对齐了,而我实际上想要它左对齐但位于文本的右侧。这可行吗? - Jimmy
不,省略号必须应用于块级或内联块级元素,不能应用于内联元素。此属性仅影响在其内联进度方向上溢出的块容器元素中的内容。更多... - skobaljic

0
或者你可以使用一个JS函数来裁剪你的文本,然后用任何你想要的内容替换...。
function shorten(text, maxLength) {
var ret = text;
if (ret.length > maxLength) {
    ret = ret.substr(0,maxLength-3) + "...";
}
return ret;

}

看这里: http://html5hub.com/ellipse-my-text/

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接