---
title: "HStack"
description: "How an HStack distributes space to its children and aligns them vertically."
url: https://www.swiftuifieldguide.com/layout/hstack
markdown_url: https://www.swiftuifieldguide.com/layout/hstack.md
---
> Convenience Markdown export of the HTML page. Interactive samples, diagrams, and visualizations stay on the canonical page.
# HStack

HStack is a layout container that arranges its children horizontally, in order of definition. If the children have different heights, it vertically aligns them as well. Note that HStack and VStack use the same layout algorithm, but with the axes swapped.

> Pretty-printed code from Simple

```swift
HStack {
    Color.purple
    Text("Hello, world")
    Color.pink
}
```

> Interactive example on HTML page: Simple.

One of the unexpected effects we see above is that the view initially renders with the text on two lines, even though there's enough space to render the text without word wrapping. Without going into too much detail yet, this happens because of the way the stack proposes sizes to its children. One helpful thing to keep in mind is that, in principle, stacks try to distribute their space as evenly as possible.

Stacks always start by ordering their children according to flexibility. The horizontal flexibility is the difference between the widest and narrowest possible width of a view. For each child, the stack computes the flexibility by proposing a zero width and an infinite width. It then subtracts the two resulting widths from each other, resulting in the child's flexibility. In our example, the text is the least flexible view, so the stack proposes a third of its available space. This isn't enough to fully render the text on a single line. In the following interactive example, we can step through the algorithm of an HStack.

> Interactive example on HTML page: Simple Stack.

Here's the same example, but we've given the text a higher layout priority. Now the text is rendered at its ideal size.

> Pretty-printed code from Layout Priority

```swift
HStack {
     RoundedRectangle(cornerRadius: 8)
         .fill(.blue)
     Text("Hello, world")
        .layoutPriority(1)
     RoundedRectangle(cornerRadius: 8)
         .fill(.green)
 }
```

> Interactive example on HTML page: Layout Priority.

## Alignment {#alignment}

After all views have a horizontal position, the stack aligns the views vertically. It queries the relevant alignment guide for each child and makes sure the returned values (in terms of the child's local coordinate system) are on a single horizontal line. Note that due to the way the stack proposes, the stack might become taller than its own proposed size (for example, when using first text baseline alignment).

> Interactive example on HTML page: Alignment Sample.
