Search Unity

Please help me make a square visual element.

Discussion in 'UI Toolkit' started by RaymingW, Aug 9, 2020.

  1. RaymingW

    RaymingW

    Joined:
    Nov 11, 2017
    Posts:
    36
    Hi all,

    I want to make a visual element that shares the same width as its parents while keeping its height the same as its width.

    Is there a way to achieve this with just uxml and uss?

    Cheers!
     
  2. etienne_unity

    etienne_unity

    Unity Technologies

    Joined:
    Aug 31, 2017
    Posts:
    102
    Hi @RaymingW

    You can use the padding property to achieve this.

    padding-top: 100%;
    will pad the current element by 100% of its parent element width.

    Code (uss):
    1. .square-container {
    2.     align-items: center;
    3.     flex-grow: 1;
    4.     justify-content: space-around;
    5.     flex-direction: column;
    6. }
    7.  
    8. .square {
    9.     padding-top: 100%;
    10.     flex-direction: column;
    11.     align-items: center;
    12.     justify-content: center;
    13.     width: 100%;
    14. }
    Code (uxml):
    1. <ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements" xsi="http://www.w3.org/2001/XMLSchema-instance" engine="UnityEngine.UIElements" editor="UnityEditor.UIElements" noNamespaceSchemaLocation="../../UIElementsSchema/UIElements.xsd" editor-extension-mode="False">
    2.     <ui:VisualElement class="square-container">
    3.         <Style src="SquareElement.uss" />
    4.         <ui:VisualElement class="square" style="background-color: rgba(0, 0, 255, 255);">
    5.             <ui:Label text="Square" style="color: rgba(255, 255, 255, 255); -unity-font-style: bold; position: absolute; -unity-text-align: middle-center;" />
    6.         </ui:VisualElement>
    7.         <ui:VisualElement class="square" style="background-color: rgba(255, 0, 0, 255);">
    8.             <ui:Label text="Square" style="color: rgb(255, 255, 255); -unity-font-style: bold; position: absolute; -unity-text-align: middle-center;" />
    9.         </ui:VisualElement>
    10.     </ui:VisualElement>
    11. </ui:UXML>
     
  3. RaymingW

    RaymingW

    Joined:
    Nov 11, 2017
    Posts:
    36
    Thank you.
     
  4. Untitled_B

    Untitled_B

    Joined:
    Oct 22, 2021
    Posts:
    1
    Hi, is there a way to do that but for a VisualElement that shares the same height as its parent while keeping its width the same as its height.
    I can't get it working by inverting the values (flex-direction: column -> row, width: 100% -> height: 100%, padding-top: 100% -> padding-left: 100% etc...).
     
  5. jakob-leitner

    jakob-leitner

    Joined:
    Nov 11, 2020
    Posts:
    18
  6. AlexandreT-unity

    AlexandreT-unity

    Unity Technologies

    Joined:
    Feb 1, 2018
    Posts:
    377