← Pixel Dreamer Studio

A wrapped Label that is as wide as its text, up to a limit

Autowrap needs a width from somewhere. Set one that follows the text.

A Label with autowrap on has no width of its own, so inside a container that sizes itself to its content, nothing gives it one. In our Godot 4.7 test a quest line in a PanelContainer came out 1 px wide, 82 lines and 2,129 px tall, about one letter per line, and the same happened next to an icon in an HBoxContainer. A minimum width of 320 px wrapped it into 3 lines, but also made a short Thank you! 320 px wide. Setting the minimum width to the text's own width, capped at 320, gave 3 lines for the long text and an 85 px box for the short one.

The code

Save it as fit_label.gd, load it with const FitLabel := preload("res://fit_label.gd") and call FitLabel.fit(label, 320) after setting the text. Call it again every time the text changes. It turns autowrap on for you.

extends RefCounted
## Makes a word-wrapped Label as wide as its text, up to a limit, so a short
## line stays on one line and a long one wraps at max_width instead of
## collapsing to one word per line inside a container that has no width to give.
##   FitLabel.fit($Panel/Label, 320)      # call again after changing the text
## Works for tooltips, speech bubbles, dialogue boxes and quest windows.


static func fit(label: Label, max_width: float) -> void:
	label.autowrap_mode = TextServer.AUTOWRAP_OFF
	label.custom_minimum_size.x = 0
	var one_line := label.get_minimum_size().x  # the text's own width on one line
	label.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
	label.custom_minimum_size.x = minf(one_line, max_width)

What we measured

A 98-character quest line and a short Thank you!, each in a PanelContainer with a VBoxContainer inside, sized by their content, in the default theme. Two runs gave the same sizes.

Why it happens

Without wrapping, a Label's minimum width is its whole line of text. With wrapping, the text can be broken anywhere, so the Label asks for almost no width, and a container that sizes itself to its children gives it exactly that. The Label then wraps at that width, which leaves room for one or two letters per line, and grows taller to fit them. The script measures the text with wrapping off first, then turns wrapping on with that width as the minimum, but never more than your limit.

What to change

Windows to put the text in: Xianxia UI & Formation Circles has 8 window styles, 24 formation circles, bars, HUD slots and realm badges, every PNG also at @2x, with Godot 4 themes.

Tested in Godot 4.7 with the Compatibility renderer.

Ready-made: Xianxia UI & Formation Circles has 8 window styles, 24 formation circles, bars, HUD slots and realm badges, every PNG also at @2x, with Godot 4 themes.

More how-tos: UI and HUD