it is possible if you know the length of the username but you have to do some math
first,
you have to determine the maximum length of the username that is possible to show in the box without overflowing.
then you have to add just one character to the end of it so it overflows then change font size until it fits again.
do it again to get the difference between each character and font size for your font and box width.
in the demo below for the box with a width of 48px and font size of 13.2px 6 characters fit but for 7 characters I need to subtract 2 px from font size and for 7 characters 1px more, and so on.
since each character from each other needs 1px but the first overflow character needs 1.2px more we need to add 1.2px at the end.
box width |
48 |
48 |
48 |
48 |
font size |
13.2px |
10.2px |
9px |
8px |
characters |
6 |
7 |
8 |
9 |
font-size:calc(var(--fontsize) - calc(calc(var(--usernamelength) - var(--maxusernamelength)) + 1.2px))
I used HTML style to create a CSS variable for username length so I can use it in CSS. 9px means 9 characters
:root{
--maxusernamelength:6px;
--fontsize:13.2px;
}
.username {
text-transform: uppercase;
width: 48px;
text-align: center;
padding-top: 2px;
overflow:hidden;
font-size:calc(var(--fontsize) - calc(calc(var(--usernamelength) - var(--maxusernamelength)) + 1.2px))
}
<div class="username" style="--usernamelength:9px">
testttest
</div>