Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question How to have width of parent element be based on child Label?

Discussion in 'UI Toolkit' started by Edvard-D, Jan 11, 2023.

  1. Edvard-D

    Edvard-D

    Joined:
    Jun 14, 2012
    Posts:
    124
    Hey all!

    I have an element (A) that is the parent of a Label. I want the size of the parent to be determined by the Label's text. The problem is that element A is itself a child of another element (B) and is expanding to fill the entire width of B.

    The flex-grow value for element A and the Label are both 0. The only way I've been able to get the size of A to change is to set a specific width, but then it won't be based on the size of the Label.

    This is what the hierarchy looks like. TemplateContainer also has a flex-grow value of 0.



    Any thoughts on how to go about this?
     
  2. C-UITools

    C-UITools

    Unity Technologies

    Joined:
    Jun 23, 2021
    Posts:
    22
    Hello,
    For this, you're going to want 2 VisualElements and a Label like so:
    - VisualElement1
    - VisualElement2
    - Label​

    Label should not have any Shrink or Grow.
    VisualElement2 does not need any special value.
    VisualElement1 should have its
    align-items
    property set to
    flex-start
    ,
    center
    , or
    flex-end
    .

    Does this solve your problem?
     
    spiney199 likes this.
  3. Edvard-D

    Edvard-D

    Joined:
    Jun 14, 2012
    Posts:
    124
    Yes it does, thank you very much!
     
  4. Edvard-D

    Edvard-D

    Joined:
    Jun 14, 2012
    Posts:
    124
    I've run into another issue with this. There are times when the TemplateContainer will need to have its position value set to "Absolute." When this is the case, the background color of the Label gets shrunk down to a small sliver. Changing the position to "Relative" fixes it, but I need to be able to set both.

    How should I set things up so that this doesn't happen?

    EDIT: Immediately after posting this I thought to try changing VisualElement1 to Absolute as well and that fixed it!