Please help me make a square visual element.

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!

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.

.square-container {
    align-items: center;
    flex-grow: 1;
    justify-content: space-around;
    flex-direction: column;
}

.square {
    padding-top: 100%;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 100%;
}
<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">
    <ui:VisualElement class="square-container">
        <Style src="SquareElement.uss" />
        <ui:VisualElement class="square" style="background-color: rgba(0, 0, 255, 255);">
            <ui:Label text="Square" style="color: rgba(255, 255, 255, 255); -unity-font-style: bold; position: absolute; -unity-text-align: middle-center;" />
        </ui:VisualElement>
        <ui:VisualElement class="square" style="background-color: rgba(255, 0, 0, 255);">
            <ui:Label text="Square" style="color: rgb(255, 255, 255); -unity-font-style: bold; position: absolute; -unity-text-align: middle-center;" />
        </ui:VisualElement>
    </ui:VisualElement>
</ui:UXML>

Thank you.

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…).

+1

So you basically want to keep the aspect ratio to 1:1. Have a look at this thread: