In this lesson, you will learn how to leverage Flexbox properties to create responsive UI layouts that adapt dynamically to different screen sizes and resolutions.
Moving Beyond Absolute Positioning
In Unity's UI Toolkit, the Flexbox system is the engine that handles UI layout. Instead of manually setting pixel coordinates for every element, you define the rules for how elements should behave inside a parent container. By default, every visual element in a UI Document is a flex container, and you control its children using three core properties: flex-direction, justify-content, and align-items.
Controlling Your Flow
Think of a VisualElement as a container holding a row of buttons. If you want them to sit side-by-side, you set flex-direction to row. If you want them to stack vertically, you set it to column.
Once you have your direction, you use alignment properties to distribute your "free space":
justify-content: Controls alignment along the main axis (the direction of your items). You can usecenterto cluster items, orspace-betweento force them to the edges of the container.align-items: Controls alignment along the cross axis (the opposite direction). For a row layout, this moves items up or down within their vertical space.
Here is how you might style a horizontal button bar in a USS file:
.button-container {
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
width: 100%;
}
Dynamic Resizing
Flexbox truly shines when you use the flex-grow property. If you set flex-grow: 1 on a child element, that element will automatically expand to fill any remaining empty space in the container. This is vital for responsive design—if your container grows because the user resized their game window, your UI elements will stretch or shrink fluidly rather than breaking or overlapping. By relying on these rules instead of hardcoded positions, you ensure your UI remains functional across mobile, desktop, and console aspect ratios.
Key Takeaway: Flexbox allows you to define the behavior and relationship of UI elements through layout rules, ensuring your interface remains consistent and responsive without the need for manual coordinate adjustments.