BoBoDev
BoBoDev

Reputation: 877

How to do text-overflow: ellipsis in reverse?

This CSS:

text-overflow: ellipsis;

Changes "StartOfLineMiddleOfLineEndOfLine" into "StartOfLineMiddleOfLineEndOf..." when there is an overflow. How do I this in reverse, making it "...OfLineMiddleOfLineEndOfLine"? Is there any workaround? I am ok with "fLineMiddleOfLineEndOfLine" without the "..." as well.

So far, I can do something slightly ok. Like

      <div style="float: right; overflow: hidden; white-space: nowrap;">
        <div>
          StartOfLineMiddleOfLineEndOfLine
        </div>
      </div>

This one truncates the prefix, but I want the text to align to the left instead.

Upvotes: 3

Views: 3734

Answers (2)

yPhil
yPhil

Reputation: 8357

As this article suggests, dir="rtl" will only work in Firefox-based browsers, and in Chrome the right of the text will be clipped as well.

The article suggests a (vaguely) portable CSS-based solution, but it's quite hackish:

    .reverse-ellipsis {
      text-overflow: clip;
      position: relative;
      background-color: white;
    }
    
    .reverse-ellipsis:before {
      content: '\02026';
      position: absolute;
      z-index: 1;
      left: -1em;
      background-color: inherit;
      padding-left: 1em;
      margin-left: 0.5em;
    }
    
    .reverse-ellipsis span {
      min-width: 100%;
      position: relative;
      display: inline-block;
      float: right;
      overflow: visible;
      background-color: inherit;
      text-indent: 0.5em;
    }
    
    .reverse-ellipsis span:before {
      content: '';
      position: absolute;
      display: inline-block;
      width: 1em;
      height: 1em;
      background-color: inherit;
      z-index: 200;
      left: -0.5em;
    }
<h2>Ellipsis is simple.</h2>
    <div class="box  ellipsis">Here is some long content that doesn't fit.</div>
    <div class="box  ellipsis">Here is some that does fit.</div>
    
    <h2>What about reverse ellipsis?</h2>
    <p>The goal would be to add ellipsis on the beginning and show the end of the content. Any idea?</p>
    <div class="box  ellipsis  reverse-ellipsis"><span>Here is some long content that doesn't fit.</span></div>
    <div class="box  ellipsis  reverse-ellipsis"><span>Here is some that does fit.</span></div>

AND the content will still be aligned right even if it's short enough to fit in the content.

Upvotes: 0

Temani Afif
Temani Afif

Reputation: 272789

Change the direction if you want the ellipsis.

.box {
  overflow: hidden;
  white-space: nowrap;
  width: 120px;
  text-overflow: ellipsis
}
<div dir="rtl" class="box">
  StartOfLineMiddleOfLineEndOfLine
</div>

And use flexbox if you don't need it:

.box {
  overflow: hidden;
  white-space: nowrap;
  width: 120px;
  display: flex;
  justify-content: flex-end;
}
<div class="box">

  StartOfLineMiddleOfLineEndOfLine

</div>

Upvotes: 7

Related Questions