Jan Tojnar
Jan Tojnar

Reputation: 5524

How to ellipsize overflowing text followed by a badge?

I have a sidebar containing a list of categories, each of them followed by a badge with a number of unread articles in it. Since the categories are user-defined, they can occasionally be longer than the width of the sidebar and thus need to be ellipsized.

Now, my code ellipsizes the items but does so for the whole row, including the badge, which I would like to keep visible. I also want to have the badge just next to the label, not floated to the right.

ul {
  width: 6em;
  background: pink;
  padding: 0.5em;
  list-style: none;
}

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

.badge {
  color: gray;
}
<ul>
  <li>Short <span class="badge">5</span></li>
  <li>Much longer item <span class="badge">13</span></li>
  <li>Another <span class="badge">2</span></li>
</ul>

I have come up with a flexbox-based solution but it requires an extra element. Is there a better way to do this?

Upvotes: 2

Views: 1534

Answers (2)

soulshined
soulshined

Reputation: 10612

Here is another flex solution, with the option of many 'badges' or elements

.wrapper {
  display: flex;
  flex-direction: column;
  padding: 10px;
  margin: 30px 0;
  background: rgba(0, 0, 0, 0.1);
}

.flex {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.will-truncate {
  flex: 1;
  min-width: 0;
}

.will-truncate h2 {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.badges > div {
  width: 30px;
  height: 30px;
  border-radius: 10px;
  background: cornflowerblue;
  display: inline-flex;
}


/*nonessentials*/

body {
  padding: 40px;
}

h2 {
  font-size: 1rem;
  font-weight: normal;
}
<div class="wrapper">

  <div class="flex will-truncate">
    <h2>This is a long string that is OK to truncate please and thank you</h2>
    <div class="flex badges">
      <div></div>
      <div></div>
      <div></div>
    </div>
  </div>

</div>

Upvotes: 1

Jan Tojnar
Jan Tojnar

Reputation: 5524

Using flexbox

When we wrap the label into a separate element, we can use flexbox:

ul {
  width: 6em;
  background: pink;
  padding: 0.5em;
  list-style: none;
}

li {
  display: flex;
  white-space: nowrap;
}

.label {
  text-overflow: ellipsis;
  overflow: hidden;
  margin-right: 0.25em;
}

.badge {
  color: gray;
}
<ul>
  <li><span class="label">Short</span><span class="badge">5</span></li>
  <li><span class="label">Much longer item</span><span class="badge">13</span></li>
  <li><span class="label">Another</span><span class="badge">2</span></li>
</ul>

Upvotes: 1

Related Questions