包装器中两个跨度之一上的文本溢出省略号


71

我的省略号有问题。这是我的HTML:

<div id="wrapper">
    <span id="firstText">This text should be effected by ellipsis</span>
    <span id="lastText">this text should not change size</span>
</div>

有没有办法用纯CSS做到这一点?这是我尝试过的:

#firstText
{
    overflow: hidden;
    white-space:nowrap;
    text-overflow:ellipsis;
}

#lastText
{
    white-space:nowrap;
    overflow:visible;   
}

它是这样显示的:

该文本应以省略号引起,该文本应

虽然这是我想要的结果:

该文本应为e ...此文本不应更改大小

Answers:


119

你可以这样给width#firstText

#firstText
{
    overflow: hidden;
    white-space:nowrap;
    text-overflow:ellipsis;
    width:150px;
    display:inline-block;
}

检查这个例子

http://jsfiddle.net/Qhdaz/5/


3
使用max-width而不是width对我来说效果更好。
mUser1990 '16

2
您如何解决垂直对齐问题?一个跨度比另一个跨度低。
杰里米

1
@Jeremy:删除#firstText上的“ display:inline-block”或向#lastText添加“ display:inline-block”。所以最后,两个<span>要么都具有内联块,要么没有。正确的解决方案可能取决于您的标记。
ripper17 '18

@ ripper17,这不起作用。在jsfiddle中,#firstText和#lastText都是内联块,但它们未垂直对齐。删除两个内联块也不能解决问题。
Frikster

1
@杰里米:只需添加vertical-align:middle; 在#firstText中。更新提琴:jsfiddle.net/68xgrqvm
Harshad Vekariya

11

您可以通过更改跨度的顺序并为第一个跨度赋予浮点数来实现此目的。这样,您不必为任何元素设置宽度:

#firstText
{
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

#lastText
{
    float:right;
    white-space:nowrap;
}
<div id="wrapper">
    <span id="lastText">this text should not change size</span>
    <span id="firstText">This text should be effected by ellipsis</span>
</div>


1
当您无法指定宽度时的绝佳方法。display: block;似乎有所不同。
weltschmerz 2015年

10

仍然有一个小案件没有处理:

如果您有未知的或动态的包装大小,并且希望第一个孩子占用所有可用空间,但是如果省略号仍然太长,则省略号。

这是我使用flexCSS属性的解决方案:

#wrapper{
    display: inline-flex;
    flex-flow:row nowrap;
    max-width:100%; /* or width:100% if you want the spans to take all available space */
}
#firstText{
    flex:1;
    white-space:pre;
    overflow: hidden;
    text-overflow: ellipsis;
}
#lastText{
    white-space:nowrap;
}

1
我没有按原样工作(在IE 11中测试)。要么max-width应该是width,要么inline-flex应该是flex
Alex311

1

您可以像这样伪造它:更改spandiv并更改CSS:

#firstText
{
    float: left;
    width: 250px;
    height: 20px;
    overflow: hidden;
    white-space:nowrap;
    text-overflow:ellipsis;
}

#lastText
{
    float: left;
    white-space:nowrap;
    overflow:visible;   
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.