Unity UI Toolkit provides built-in support for auto-sizing text elements, allowing text to automatically scale to fit within its container.

Unity Documentation

For the most up-to-date information, see the official Unity documentation:

Unity Manual: Auto-sizing text elements

Overview

Auto-sizing text adjusts the font size dynamically based on the available space, ensuring text remains readable and fits within defined boundaries. This is useful for:

  • Responsive UI layouts
  • Localization (different languages have different text lengths)
  • Dynamic content that varies in length

USS Properties

Enable Auto-Sizing

css
.auto-size-label { -unity-font-size-auto-sizing: true; }

Min/Max Font Size

Control the range of font sizes the auto-sizing algorithm will use:

css
.auto-size-label { -unity-font-size-auto-sizing: true; -unity-font-size-auto-sizing-min-size: 12px; -unity-font-size-auto-sizing-max-size: 48px; }

Step Size

Controls the granularity of size adjustments:

css
.auto-size-label { -unity-font-size-auto-sizing: true; -unity-font-size-auto-sizing-step-size: 1px; }

Complete Example

css
.dynamic-title { -unity-font-size-auto-sizing: true; -unity-font-size-auto-sizing-min-size: 16px; -unity-font-size-auto-sizing-max-size: 64px; -unity-font-size-auto-sizing-step-size: 2px; /* Container must have defined dimensions */ width: 300px; height: 100px; /* Other styling */ -unity-text-align: middle-center; white-space: normal; }

UXML Usage

xml
<ui:Label text="This text will auto-size" class="dynamic-title" />

Code Usage

csharp
Label label = new Label("Dynamic text"); label.style.unityFontSizeAutoSizing = true; label.style.unityFontSizeAutoSizingMinSize = 12; label.style.unityFontSizeAutoSizingMaxSize = 48;

Important Notes

  1. Container Size Required: Auto-sizing only works when the container has defined dimensions. Without explicit width/height, the text cannot determine how to scale.

  2. White Space: Set white-space: normal if you want text to wrap before scaling down.

  3. Performance: Auto-sizing recalculates on layout changes. Avoid using it on rapidly changing text.

  4. Rich Text: Works with rich text tags, but complex formatting may affect sizing calculations.

Best Practices

  • Set reasonable min/max bounds to maintain readability
  • Use larger step sizes (2-4px) for better performance
  • Test with your longest expected text strings
  • Consider localization requirements when setting bounds

Settings

Theme

Light

Contrast

Material

Dark

Dim

Material Dark

System

Sidebar(Light & Contrast only)

Light
Dark

Font Family

DM Sans

Wix

Inclusive Sans

AR One Sans

Direction

LTR
RTL