CSS: Display only the first two letters of a string

If you don't want to go with monospaced fonts, but just want to display as many characters as you want in the available/specified width (without showing half chars), you can use the a work-break rule while making sure you're not displaying the second line:

.initials {
  display: inline-block;
  width: 40px;
  font-size: 24px;
  font-weight: 300;
  overflow: hidden;
  word-break: break-all;
  height: 80px;
  line-height: 80px
}

Example here: https://codepen.io/stevendegroote/pen/GRgjQoG

Hope this helps anyone.


Actually, there is a way to do this in pure css! It uses the ch font-dependent unit.

.two_chars{
  font-family: monospace;
  width: 2ch;
  overflow: hidden;
  white-space: nowrap;
}

.large{
  font-size: 2em;
}
<div class="two_chars">
  Some long text.
</div>
<div class="two_chars large">
  Even longer text.
</div>

Unfortunately this works only with monospace fonts and not in older browsers.


Although I agree css is primarily for styling; there are use cases for "displaying" content using:

text-overflow: ellipsis

<div class="myClass">
  My String
</div>

.myClass {
  white-space: nowrap;
  width: 39px;
  overflow: hidden;
  text-overflow: ellipsis;
}

Will show truncated "My"

Fiddle

Tags:

Css