Make buttons with text scale according to text width within horizontal layout group

Hello,

This is something that I have struggled with for a long while without finding a proper solution.

Lets say I have a horizontal layout group that has a couple of buttons in it. I want each button in the horizontal layout group to fit the text within the button.

The buttons have an image as background and a text as a child.

Imagine the following layout of gameobjects and components:

--Content
  [Horizontal Layout Group]
----Button 1
    [Image]
    [Button]
------Button Text
      [Text Mesh Pro Text]
----Button 2
    [Image]
    [Button]
------Button Text
      [Text Mesh Pro Text]

This is what I want it to look like:

The blue rectangle here is the content GameObject with the horizontal layout group.

I can add a content size fitter to the Text component in the button but this will not make the button’s background scale accordingly. I can tell the horizontal layout group to expand the children but it will not respect the text’s width. Adding a content size fitter to the button is not allowed because the horizontal layout group is the parent.

Can anyone help me out on this one? I have seen many different discussions on different forum posts but none seem to solve my issue.

Thank you in advance.

I finally managed to get this working. Leaving my solution here for anyone that needs it.

Supposedly this guide explains how to get the above working properly, but its a complicated read. I think what its trying to say is correct, and my problem was caused by something else.

In our case, the background image I was using was at least 512 pixels wide, which means that the preferred size is at least 512 pixels. This causes the button to scale to the text size, but only after 512 pixels. Replacing it with a texture that is smaller makes the above work, using the component layout mentioned in the guide:

--Content
  [Horizontal Layout Group]
  - Control Child Size (Width and Height)
----Button 1
    [Horizontal Layout Group]
    - Control Child Size (Width and Height)
    [Image]
    [Button]
------Button Text
      [Text Mesh Pro Text]
----Button 2
    [Horizontal Layout Group]
    - Control Child Size (Width and Height)
    [Image]
    [Button]
------Button Text
      [Text Mesh Pro Text]

Here are the backgrounds I was using, with the wrong one on the left: