Reputation: 19366
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?
Upvotes: 21
Views: 45638
Reputation: 2233
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.
Upvotes: 2
Reputation: 2982
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"
Upvotes: 5
Reputation: 2884
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.
Upvotes: 46
Reputation: 1430
Like you said, you can do it using nth-of-everything but it requires additional javascript.
For a single letter you can do this :
#txt {
visibility: hidden;
}
#txt::first-letter {
visibility: visible;
}
<p id='txt'>hello</p>
here is the fiddle : https://jsfiddle.net/nvf890vo/
For multiple letters you have to mix with html, for example :
<p><span class='show'>He</span>llo</p>
And apply the visible state to class "show".
Upvotes: 1