bsparacino
bsparacino

Reputation: 353

Text Overflow - Prevent from clipping letters in half

For my situation, I have a fixed width in which I can show a name. If the name is too long, then I need to clip/hide the name.

The issue I am having is the last letter is being cut in half, whereas I would only like that last whole letter to show.

In the example below for "HelloWorld!", the 'W' is cut in half. Instead I need it to ignore that partial letter and just show "Hello". Is this even possible with just CSS?

.test {
  white-space: nowrap;
  width: 44px;
  overflow: hidden;
  text-overflow: clip;
  border: 1px solid #000000;
}
<div class="test">HelloWorld!</div>

Upvotes: 7

Views: 5415

Answers (3)

Shashank Bhatt
Shashank Bhatt

Reputation: 857

The text-overflow property's clip value is used to clip the text which is the default value itself when nothing is specified. This value is meant to be used for clipping only.

However there might be some cases when last letter is even clipped with ellipsis value. In that case you just need to make the element's display to inline-block

span {
  max-width: 90px;
  overflow: hidden;
  white-space: nowrap;
  display: inline-block;
  text-overflow: ellipsis;
}
<span>somelong lon g text text texxt</span>

In this example try changing span's default display which is inline and see that text-overflow will have no effect.

And after that if you don't need ... then you can simply add one absolutely positioned ::after pseudo and make it background white thus removing ... effect at the end.

Upvotes: 0

Roman Maksimov
Roman Maksimov

Reputation: 1635

.test {
  width: 44px;
  height: 18px;
  word-break: break-all;
  overflow: hidden;
  border: 1px solid #000000;
}
<div class="test">HelloWorld!</div>

Upvotes: 5

Temani Afif
Temani Afif

Reputation: 273512

You can consider ellipsis instead of clip:

.test {
  white-space: nowrap;
  width: 44px;
  overflow: hidden;
  text-overflow: clip;
  border: 1px solid #000000;
}

.test2 {
  width: 44px;
  overflow: hidden;
  border: 1px solid #000000;
}

.test2>span {
  display: block;
  width: calc(100% + 10px);
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}
<div class="test">HelloWorld!</div>

<div class="test2"><span>HelloWorld!</span></div>
<div class="test2"><span>Sometext</span></div>
<div class="test2"><span>Myname</span></div>

UPDATE

You can also consider word-break but in this case you need to have a fixed height also:

.test {
  width: 44px;
  height:20px;
  overflow: hidden;
  word-break:break-all;
  border: 1px solid #000000;
}
<div class="test">HelloWorld!</div>
<div class="test">Myname</div>
<div class="test">sometext!</div>

Upvotes: 1

Related Questions