-1

I stream on Twitch, and I have an overlay below my facecam that displays the username of somebody who's interacted with my stream recently. Whenever a username is too long to fit in the aforementioned facecam overlay it gets pushed halfway off the bar, rendering the text unreadable. What is the easiest way to make a username auto-scale based on its length, using CSS?

This is what the CSS code for the username looks like at the moment:

.username {
  text-transform: uppercase;
  font-family: {{fontFamily}};
  width: 100%;
  text-align: center;
  padding-top: 2px;
}

With a normal length username:

Normal Length Username

With a long username:

Long Username

Jacob Lockard
  • 1,195
  • 9
  • 24
  • 1
    Well the most easiest method will be not defining `height` property values or keeping it value as auto . This way background will cover all the text . Use `overflow: auto` with easy solution too if only `height:auto` won't work – Rana Oct 24 '21 at 21:04
  • https://stackoverflow.com/questions/16056591/font-scaling-based-on-width-of-container – Paulie_D Oct 24 '21 at 21:13

1 Answers1

0

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>
pfndesign
  • 174
  • 3
  • 12