Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS: Display only the first two letters of a string

Tags:

css

Is it possible to display only the first two letters of a string using pure CSS?

So far I have tried (without success):

  • :first-letter (targets only the first letter and does not work for me anyway)
  • :nth-of-everything (requires additional javascript)
  • text-overflow: ellipsis; (is adding points)
  • overflow: hidden; (only works if the text-size does not change, clumsy solution)

Is there another way?

like image 429
Blackbam Avatar asked Feb 10 '16 23:02

Blackbam


People also ask

How do you display part of a string?

The substr() method extracts a part of a string. The substr() method begins at a specified position, and returns a specified number of characters. The substr() method does not change the original string. To extract characters from the end of the string, use a negative start position.

How do I show only the first letter in CSS?

CSS ::first-letter Selector The ::first-letter selector is used to add a style to the first letter of the specified selector. Note: The following properties can be used with ::first-letter: font properties. color properties.


2 Answers

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

like image 23
Fergus Avatar answered Sep 20 '22 13:09

Fergus


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.

like image 139
fl0cke Avatar answered Sep 20 '22 13:09

fl0cke