Shrink UI text background image to fit text

I want to create UI text elements with backgrounds that resize to fit around the text. I’ve tried to follow guides which use vertical layout groups to achieve this. What I have at the moment partially works. The image and text resize as more text is added. But the height of the background image won’t shrink below 110 (see top text).

198496-resizingtext.png

I can see that the preferred height of the background image is 110, but I’m not sure what determines this. When I try using a LayoutElement to change the Preferred Height, this breaks the auto-resizing behaviour that I want.

The UI hierarchy is:
198498-resizingtext2.png

“Contents Container” with VerticalLayoutGroup options enabled:

  • Control Child Size: Width + Height
  • Child Force Expand: Width.

“Heading Background” with VerticalLayoutGroup options enabled:

  • Control Child Size: Width + Height

“Heading Text” using TextMeshProUGUI.

Couldn’t find any solutions for this, so used a workaround. I created a custom Image implementation that uses the layout group’s (VerticalLayoutGroup) preferred height as the preferred height, rather than the image height.

So the Image components on Heading Background and Detail Background are using this script:

public class ContentFitImage : Image
{
    public override float preferredHeight
    {
        get
        {
            if (TryGetComponent<LayoutGroup>(out var layoutGroup))
            {
                return layoutGroup.preferredHeight;
            }

            return base.preferredHeight;
        }
    }
}