Skip to main content

Laying out a Yoga tree

Each box in Yoga is represented as a Yoga Node. These nodes form a tree which is used to store both input styles, and output layout results.

Building a Yoga tree

Yoga nodes may be created, styled, and linked together. See Styling for a more comprehensive reference of how to style a Yoga Node.

#include <yoga/Yoga.h>

YGNodeRef root = YGNodeNew();
YGNodeStyleSetFlexDirection(root, YGFlexDirectionRow);
YGNodeStyleSetWidth(root, 100.0f);
YGNodeStyleSetHeight(root, 100.0f);

YGNodeRef child0 = YGNodeNew();
YGNodeStyleSetFlexGrow(child0, 1.0f);
YGNodeStyleSetMargin(child0, YGEdgeRight, 10.0f);
YGNodeInsertChild(root, child0, 0.0f);

YGNodeRef child1 = YGNodeNew();
YGNodeStyleSetFlexGrow(child1, 1.0f);
YGNodeInsertChild(root, child1, 1.0f);

Yoga Nodes are not freed automatically and should be discarded when no longer needed. Individual nodes may be freed by calling YGNodeFree(node), or an entire Yoga tree may be freed by calling YGNodeFreeRecursive(node).

Laying out the tree

The full tree of Yoga nodes is laid out all at once. This layout may be constrained to a passed availableWidth and availableHeight, or may be allowed to expand infinitely in a given axis by passing Undefined.

YGNodeCalculateLayout(root, YGUndefined, YGUndefined, YGDirectionLTR);

Reading layout results

Layout results are now written to each Yoga node. This includes an offset relative to the border box of the node's parent, along with dimensions, and the resolved values for margin, border, and padding for each physical edge.

float left = YGNodeLayoutGetLeft(child0);
float height = YGNodeLayoutGetHeight(child0);