Flex
Flex is Box with display: flex
and comes with helpful
style shorthand. It renders a div
element.
Import#
import { Flex, Spacer } from "@chakra-ui/react"
- Flex: A
Box
withdisplay: flex
. - Spacer: Creates an adjustable, empty space that can be used to tune the
spacing between child elements within
Flex
.
Usage#
Using the Flex components, here are some helpful shorthand props:
flexDirection
isdirection
flexWrap
iswrap
flexBasis
isbasis
flexGrow
isgrow
flexShrink
isshrink
alignItems
isalign
justifyContent
isjustify
While you can pass the verbose props, using the shorthand can save you some time.
Box 1
Box 2
Box 3
Editable Example
Using the Spacer#
As an alternative to Stack
, you can combine Flex
and Spacer
to create
stackable and responsive layouts.
Box 1
Box 2
Editable Example
Flex and Spacer vs Grid vs Stack#
The Flex
and Spacer
components, Grid
and HStack
treat children of
different widths differently.
- In
HStack
, the children will have equal spacing between them but they won't span the entire width of the container. - In
Grid
, the starting points of the children will be equally spaced but the gaps between them will not be equal. - With
Flex
andSpacer
, the children will span the entire width of the container and also have equal spacing between them.
Flex and Spacer: Full width, equal Spacing
Grid: The children start at the beginning, the 1/3 mark and 2/3 mark
HStack: The children have equal spacing but don't span the whole container
Editable Example
A good use case for Spacer
is to create a navbar with a signup/login button
aligned to the right.
Chakra App
Editable Example
Props#
Name | Type | Description | Default |
---|---|---|---|
align | SystemProps["alignItems"] | Shorthand for `alignItems` style prop | - |
basis | SystemProps["flexBasis"] | Shorthand for `flexBasis` style prop | - |
direction | SystemProps["flexDirection"] | Shorthand for `flexDirection` style prop | - |
grow | SystemProps["flexGrow"] | Shorthand for `flexGrow` style prop | - |
justify | SystemProps["justifyContent"] | Shorthand for `justifyContent` style prop | - |
shrink | SystemProps["flexShrink"] | Shorthand for `flexShrink` style prop | - |
wrap | SystemProps["flexWrap"] | Shorthand for `flexWrap` style prop | - |