What is a FlexContainer?

CSS equivalent: “FlexContainer

CSS classifies all elements as a “FlexContainer”, a “FlexItem” or (in nested layouts): both. In CSS3, any element with “display: flex” is a ‘FlexContainer’.

In Unity we need a way to ‘take-over’ from Unity’s built-in layout system and replace it with Flexbox. This MonoBehaviour (FlexContainer) does that. Attaching a FlexContainer component to a GameObject is exactly the same as writing “display: flex” in CSS3.

When to use FlexContainer

The only way to create a layout – or to arrange the items, to decide what goes where etc – is using FlexContainers.

You start with one FlexContainer (the special RootFlexContainer) which represents your whole screen (or, if you’re embedding inside a large screen: represents the maximum area Flexbox will render into), and then you add child FlexContainers, and inside them grandchild FlexContainers, as many as you need to describe your desired layout.

FlexContainers will only manage child GameObjects that have a FlexItem attached.

This means that when you nest one FlexContainer inside another then the child FlexContainer will also need a FlexItem on it. This is handled automatically if you use the built-in shortcuts or API calls for ‘adding a child FlexContainer’.

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

There is no integration between UnityUI and FlexContainer – they are incompatible. FlexContainer fully replaces UnityUI for layout and sizing and positioning.

Controlling layout using FlexContainers

If you’re familiar with CSS3-Flexbox then you already know how to use FlexContainers – they have the same properties (flex-direction, align-items, align-content, justify, etc) and work the same way.

There is one special case: CSS3 margins/padding are handled specially. Eventually the goal is for “margins” to be part of the FlexItem and “padding” to be part of the FlexContainer (padding only applies to child-items, and margins only apply to self). But for historic reasons both settings are currently stored on the FlexItem: if you want to set the padding of a FlexContainer, and have it affect the child positions, you need to edit the FlexItem that’s attached to the FlexContainer. This will change in v4 or v5.

If you’ve never used CSS3 before, or never used Flexbox, here are some recommended tutorials: