What is a FlexItem?
CSS equivalent: “FlexItem“
CSS classifies all elements as a “FlexContainer”, a “FlexItem” or (in nested layouts): both. In CSS3, any element whose parent has “display: flex” is a ‘FlexItem’.
In Unity we need a place to store the CSS3-specific features of each UI element – e.g. “max-width”, “flex-basis”, “flex-grow”, etc. We also need a way for you to mark specific UI elements as ‘being laid-out by Flexbox’ vs ‘being laid-out by UnityUI. This MonoBehaviour (FlexItem) serves both purposes.
When to use FlexItem
Every UI element that you want positioned or sized (or both) by Flexbox must have a FlexItem MonoBehaviour controlling it. The easiest way to do this is to attach a FlexItem directly to the element’s GameObject.
NB: you can also create an empty GameObject, attach a FlexItem, and then drag/drop your UI element as a child of this GameObject. For some UI elements this gives you more precise control – e.g. it’s especially good for Images and Buttons, where you want to do fine-tweaking of their size using UnityUI/RectTransform controls.
A FlexItem does nothing until it has a parent FlexContainer. The FlexContainer reads the information from all its FlexItem children, then sets the sizes of each of them, and finally positions them all within itself.
Integration with UnityUI
FlexItem is compatible with UnityUI – it is a standard RectTransform, and you can embed other RectTransforms inside it and they will be laid out by UnityUI. (but bear in mind the note above: unless the FlexItem has a parent FlexContainer, it won’t do anything at all).
This is frequently used to e.g. make a layout in Flexbox and then place ‘background images’ in each of the FlexItems. If you set the RectTransform anchors appopriately then UnityUI/RectTransform will keep the images always precisely filling their parent FlexItem’s space – while Flexbox will decide and position the space.
NB: when doing this, make sure that the ‘background image’ GameObject is the first child of the FlexItem: Unity’s UI systems (including the new UIToolkit) don’t implement render-order correctly, and will always place the first child behind the second, the second behind the third, etc.
Controlling an item’s size using FlexItem
There are three parts to sizing an item in Flexbox: Each element (image, text, etc) has an ‘intrinsic size’, each element has FlexItem properties (max-width, min-width, etc), and finally the element’s parent FlexContainer decides when to grow/shrink the item based on available space.
All the ‘flex’ properties from CSS3 appear on the FlexItem and you can set the in the inspector.
Intrinsic size depends on the LayoutAlgorithm you’re currently using. As of Summer 2022 the main LayoutAlgorithm (v4.0.10) intelligently examines each FlexItem, looks at the UnityUI elements that are attached and are children (e.g. Button, Text, Image, etc), and calculates an appropriate, correct, intrinsic size.