Shrink UI text background image to fit text

I’ve asked this on Unity answers but not sure which place gets more traffic.

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).
8349291--1098585--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.
8349291--1098594--upload_2022-8-9_17-8-1.png

If I use a LayoutElement on the image with Preferred Height set:
8349291--1098597--upload_2022-8-9_17-9-46.png

The UI hierarchy is:
8349291--1098588--resizingtext3.PNG
Contents Container and Heading Background have a VerticalLayoutGroup components with settings:
8349291--1098591--upload_2022-8-9_17-6-2.png

Does anyone know how I can change the preferred height of the background image while still having the background+text autosize to fit the text? Thanks!

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;
         }
     }
}