Home > Enterprise >  How to apply 'text-overflow:ellipsis' subject with badge text on right?
How to apply 'text-overflow:ellipsis' subject with badge text on right?

Time:03-13

I tried to make a fixed-width line which contains book title and badge text, which shortens the title and add ellipsis when length of title and badge text is too long.

When the badge is on the left of the title, it can be easily done with overflow:hidden text-overflow:ellipsis. for example,

| [Sold Out] The Stackoverflow Book                    |
| [Sold Out] the quick brown fox jumps over the laz... |
| [Pre-Order Now] the quick brown fox jumps over th... |
| [Only 3 left in stock] the quick brown fox jumps ... |

it worked well with overflow:hidden text-overflow:ellipsis. But I coudln't figure out how to achieve the same result when the badge text is on the right. for example,

| The Stackoverflow Book [Sold Out]                    |
| the quick brown fox jumps over the laz... [Sold Out] |
| the quick brown fox jumps over th... [Pre-Order Now] |
| the quick brown fox jumps ... [Only 3 left in stock] |

How can I achiveve proper ellipsis display with badge text on right? (badge must show all the text they have)

CodePudding user response:

Try using display: flex with margin-left: auto for the badge.

HTML:

<div class=line>
<div class=subject>
The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.
</div>
<div class=badge>
[Sold Out]</div>
</div>

<div class=line>
<div class=subject>
The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.
</div>
<div class=badge>
[Pre-Order Now]
</div>
</div>
<div class=line>
<div class=subject>
The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.
</div>
<div class=badge>
[Only 3 left in stock]
</div>
</div>

CSS:

.line {
  display: flex;
}
.subject {
    white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.push {
  margin-left: auto;
}
.badge {
  white-space: nowrap;
}

JSFiddle: https://jsfiddle.net/ftbLph2m/3/

CodePudding user response:

Using flex this should turn out fairly easy.

.book {
  display: flex;
  flex-wrap: nowrap;
  width: 100%;
  max-width: 300px;
}

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

.status {
  white-space: nowrap;
}
<p >
  <span >the quick brown fox jumps over the lazy dog</span>
  <span >[Sold Out]</span>
</p>

<p >
  <span >the quick brown fox jumps over the lazy dog</span>
  <span >[Pre-Order Now]</span>
</p>

<p >
  <span >the quick brown fox jumps over the lazy dog</span>
  <span >[Only 3 left in stock]</span>
</p>

  • Related