Fitting a parent UI element to a Child Text's Content

As the attachment illustrates I have an Image element to function as the panel behind its child Text element whose content dynamically changes at runtime, and want to make the parent adjust size to fit.

I’ve tried adding a Content Size Fitter and Layout Element to both the parent and child, and fiddled with both their vertically-oriented parameters. What’s the magic combination?

A little more fiddling yielded fruit. For posterity, the combination that worked was:

  • No special components on the text child.
  • A Content Size Fitter on the parent with Horizontal Fit at “Unconstrained”, Vertical Fit “Preferred Size”.
  • A Vertical Layout Group on the parent (according the docs it would be just as well for a Horizontal given only one child), with proper padding and Child Alignment to “Middle Center”.
  • To keep it at the top-left corner, set the parent’s “Pivot” to (0,1).

If you don’t mind using two canvases, here’s one way to do it:

Canvas
    Text (ContentSizeFitter, prefer veritcal/horizontal)
        Canvas (stretch width and height, override sorting to render behind Text)
            Parent (stretch)