How to do scalable text box UI elements in Unity
After taking a deep dive into Unity’s UI features, I ran into a pernicious problem. There was a no way, to my knowledge, to set a maximum size of a UI element, while also wanting it to scale down to the minimum size of a variable text box! Constraining your UI elements to a max size is super important, because otherwise you have text boxes that could exceed the size of the screen.
So when you set a ‘Preferred Size’ in Layout Element, using Horizontal Layout Group and Content Size Fitter, you get:
Note how the text is dwarfed by a never-changing size of the text box. While Unity has components that scale UI elements based on other elements, there was no intuitive solution on how to define a max range without this as a result.
Luckily I stumbled upon a Unity forum post from 2014 that, halfway down the page, showed how to sort of do what I was looking for: Why doesn't Layout Element have Max values?
As it turns out, I needed to re-arrange my hierarchy. Rather than have the text and image on the same GameObject, I needed to place them all on nested GameObjects parented by a container object (that itself is a child of the UI Canvas, of course):
Of course, being from 2014, the forum post is now slightly incorrect, so let me explain what these objects are:
Container object
HorizontalLayoutGroup with ChildForceExpand set to false, and ChildControlsSize set to true for both Width and Height
ContentSizeFitter with horizontal/vertical unconstrained
Set the width and height of the transform to the max width/height you want
Nothing visual on it
Image object (as child of Container object)
HorizontalLayoutGroup with ChildForceExpand set to false, and ChildControlsSize set to true for both Width and Height
Background image (a Sprite that’s been 9-sliced, and set to Image Type “Sliced”)
Text object (as child of Image object)
Text
And that results in perfectly scalable elements:
You can also choose to set ChildForceExpand/ChildControlsSize for only Width or only Height, or set the ContentSizeFitter to Preferred for Horizontal or Vertical, to create different results that suit your project.
Figured I’d go ahead and take what I learned and shout about it from the rooftops. I’m still astounded that the solution is this un-intuitive, and the answer buried so deeply. A quick google search reveals that a lot of people seem to have this problem, so hope it helps!













