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

我有省略号的问题,这是我的 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;
}

这就是它的表现形式:

这篇文章应该受省略号的影响

虽然这是我想要的结果:

这篇文章应该是... 这篇文章不应该改变大小

98430 次浏览

You can give width to your #firstText like this :

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

Check this example

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

You could fake it like this: change your span to div and change your CSS:

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


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

You could achieve this by changing the order of your spans and give the first span a float right. That way you don't have to set a width to any of your elements:

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


#lastText
{
color:red;
font-size:30px;
float:right;
white-space:nowrap;
}
<div id="wrapper">
<span id="lastText">this text must be shown in full</span>
<span id="firstText">This text may be cropped</span>
</div>

There's still a little case not handled:

When you have an unknown or a dynamic wrapper size and you want the first child to take all available space but ellipsis if it's still too long.

Here is my solution using flex CSS properties :

#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;
}
<div id="wrapper">
<span id="firstText">This text should be effected by ellipsis if wrapper is too small</span>
<span id="lastText">This text should be fixed and not change size</span>
</div>

If you do not want to explicitly add the width or max-width property, here is how you can do using display:flex;

#wrapper {
display: flex;
}


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


#lastText {
/* The text may wrap to next line */
white-space: nowrap;
}
<div id="wrapper">
<span id="lastText">this text must be shown in full</span>
<span id="firstText">This text may be cropped</span>
</div>

For ellipses we have to fulfill 2 basic criteria:

  • Apply overflow: hidden; text-overflow: ellipsis; white-space: nowrap; properties to the element you want to have ellipses on.

  • Somehow constraint the width of that element, whether forcefully adding width, or min-width or using display:flex; or something else entirely.