Timmy
Timmy

Reputation: 745

Show only the first letters, three dots and the last N letter of a span

If I've a very long text like this (for example in a table):

<p class='line'>
    <span class='fixed1'>FIXED</span>
    <span class='long_text'>This is my very very very very long text</span>
    <span class='fixed2'>FIXED</span>
</p>

By default the <p> width is 100% and if the text is longer than the screen it's showed on multi lines. Instead I want it in a single line where only the last N letter are showed.

Here some example:

Screen large enough:

FIXED This is my very very very very long text FIXED

Screen not enough large, text overflow.

FIXED This is my ve... text FIXED

I can obtain something similar using:

span.long_text {
    overflow: hidden;
    text-overflow: ellipsis;
}

Is it possible to obtain the effect I described? How?

Upvotes: 0

Views: 1270

Answers (2)

FelipeAls
FelipeAls

Reputation: 22161

Ellipsis only work with single line things so that's OK here. The problem is with those "N letter".

Here's a starter with :after (you must have your N last letters in some CSS. Suboptimal => https://codepen.io/PhilippeVay/pen/vWMePJ?editors=0100

.line {
  display: flex;
  border: 1px solid black;
  width: 240px;
}
.line > * {
  white-space: nowrap;
}
.long_text {
  position: relative;
  flex-grow: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  background: yellow;
  padding-right: 2rem;
}
.long_text::after {
  content: "g text";
  position: absolute;
  right: 0;
}
<p class='line'>
    <span class='fixed1'>FIXED</span>
    <span class='long_text'>This is my very very very very long text</span>
    <span class='fixed2'>FIXED</span>
</p>

It could be content: attr(data-last-letters) and <span class='long_text' data-last-letters="g text"> which now works in most browsers.
Or background-image: -moz-element(#someId); that copy-paste an element elsewhere and that only works in Firefox (for the past 7 years: won't work cross-browser anytime soon I guess).

Upvotes: 0

Idk
Idk

Reputation: 26

You can use white-space: nowrap to force it to stay in a single line.

text-overflow: ellipsis will replace the end of your content with '...' when overflow occurs. However span must be a block for text-overflow to work, so set its display property to inline-block or block.

Demo: https://jsfiddle.net/1bmdu5xd/

Upvotes: 1

Related Questions