Guide: FlexContainers vs FlexItems
What are they?
All Flexbox layouts are created by combining FlexContainers and FlexItems. FlexItems are purely used to describe the individual elements of your layout, and FlexContainers are used to control how groups of FlexItems are positioned/sized relative to each other.
See the API docs for each:
- FlexContainer - a MonoBehaviour that contains one or more FlexItems, and controls how they are laid out.
- FlexItem - a MonoBehaviour that describes a single element in your layout, and how it should be sized/positioned.
Using them in Unity / FlexBuilder
In Unity, we have to explicitly add a "FlexContainer.cs" MonoBehaviour and/or a "FlexItem.cs" MonoBehaviour to any GameObject that we want to participate in the Flexbox layout.
Tip
💡 In CSS you convert an HTML tag to a FlexContainer by adding the property "display: flex"
Tip
💡 In CSS you convert an HTML tag to a FlexItem by placing it inside a tag that is already a FlexContainer
One or both?
In a typical layout, the highest-level item in the tree is a FlexContainer, the lowest items in the tree are FlexItems, and everything in between is both a FlexItem (i.e. it's embedded inside a parent FlexContainer), and also a FlexContainer (i.e. it contains other FlexItems). So .. most of the GameObjects in a Flexbox layout will have both components attached.
However ... a common scenario is to have some of your UI generated at runtime, or procedurally from script. In this case you will typically have a FlexContainer at the bottom of the tree that has no FlexItems (it is the attachment point where you will instantiate prefabs of bits of your UI, that will finish the tree by adding a FlexItem, or by adding a complex subtree of FlexContainers that end in FlexItems).
Another common scenario is to embed some pure UnityUI inside a Flexbox layout, using Flexbox to set the overall size, and then using Unity RectTransform features to control the local UnityUI code. This is especially useful when you want to integrate other assets that only understand UnityUI. In that case you will have a FlexItem that contains child objects where the children have neither a FlexItem nor a FlexContainer.
Where do the names come from?
These terms come directly from the CSS Specification: