Position UI elements as percentage of parent object

Hi,
I’m sure that this is really simple but I cannot find a solution and I am a complete beginner.

In the scene editor I created a very simple 2d scene with a canvas and inside it some text boxes.
The textboxes are TextMeshPro objects.
I would like to set one textbox to be 20% of the width of the canvas and 50% of the height of it, and to keep these proportions if I change the dimensions of the canvas.

To do this, in the Anchors presets I select the “stretch” option and put the anchors to the corners of the parent canvas. Then I set the X scale to 0.2 and the Y scale to 0.5. This method seems to work but the problem is that also the text is scaled both in the X and Y directions and it looks weird.

Is anyway to avoid the scaling of the text or is any other method to achieve what I need?

Thanks for your help

1 Like

Yes, there are other ways to achieve what you need without scaling the text. One common approach is to use the RectTransform component to position and size UI elements as a percentage of their parent object.

Here’s a step-by-step guide on how you can do this:

  1. Select the text box you want to position and size as a percentage of the canvas.
  2. In the Inspector panel, click on the “Add Component” button and search for “RectTransform” to add it to the text box.
  3. In the RectTransform component, you’ll see several properties such as “Anchors”, “Pivot”, “Position”, “Size Delta”, and “Rotation”. These properties control the positioning and size of the text box.
  4. To set the text box to be 20% of the width of the canvas, you can adjust the “Anchor Min” and “Anchor Max” properties. These properties define the relative position of the text box’s corners within its parent canvas, where (0,0) is the bottom-left corner and (1,1) is the top-right corner. You can set the “Anchor Min” to (0,0) and the “Anchor Max” to (0.2,1) to make the text box span 20% of the canvas width.
  5. Similarly, to set the text box to be 50% of the height of the canvas, you can adjust the “Anchor Min” and “Anchor Max” properties vertically. You can set the “Anchor Min” to (0,0) and the “Anchor Max” to (0.2,0.5) to make the text box span 50% of the canvas height.
  6. You can also adjust the “Pivot” property to specify the point within the text box that acts as the anchor point for positioning and rotation. For example, you can set the pivot to (0,0.5) to align the left edge of the text box with the left edge of the canvas.
  7. Finally, you can adjust the “Position” and “Size Delta” properties to fine-tune the position and size of the text box relative to its anchor points.

By using the RectTransform component and setting the anchors and pivot points correctly, you can achieve the desired positioning and sizing of the text box as a percentage of the canvas, without scaling the text itself.