Flex
Flex is Box with display set to flex and comes with helpful style shorthand.
It renders a div element.
Import
import { Flex, Spacer } from "@chakra-ui/react";
- Flex: A
Boxwithdisplay: 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:
flexDirectionisdirectionflexWrapiswrapflexBasisisbasisflexGrowisgrowflexShrinkisshrinkalignItemsisalignjustifyContentisjustify
While you can pass the verbose props, using the shorthand can save you some time.
Using the Spacer
As an alternative to Stack, you can combine Flex and Spacer to create
stackable and responsive layouts.
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
FlexandSpacer, the children will span the entire width of the container and also have equal spacing between them.
A good use case for Spacer is to create a navbar with a signup/login button
aligned to the right.
Since Spacer renders a div, any gap value provided to the parent is
applied to both sides of this component, and therefore make the gap appear
doubled when the spacer is completely collapsed.
The example below is not responsive on purpose as you might switch to a collapsed menu on mobile.
Props
align
alignShorthand for alignItems style prop
SystemProps["alignItems"]basis
basisShorthand for flexBasis style prop
SystemProps["flexBasis"]direction
directionShorthand for flexDirection style prop
SystemProps["flexDirection"]grow
growShorthand for flexGrow style prop
SystemProps["flexGrow"]justify
justifyShorthand for justifyContent style prop
SystemProps["justifyContent"]shrink
shrinkShorthand for flexShrink style prop
SystemProps["flexShrink"]wrap
wrapShorthand for flexWrap style prop
SystemProps["flexWrap"]