Is it possible to display only the first two letters of a string using pure CSS?
So far I have tried (without success):
Is there another way?
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With