Stack
Stack is a container component for arranging elements vertically or horizontally.
Introduction
The Stack component manages the layout of its immediate children along the vertical or horizontal axis, with optional spacing and dividers between each child.
<Stack
direction="row"
spacing={2}
sx={{
justifyContent: "center",
alignItems: "center",
}}
>
Basics
import Stack from '@mui/joy/Stack';
The Stack component acts as a generic container, wrapping around the elements to be arranged.
Use the spacing
prop to control the space between children.
The spacing value can be any number, including decimals, or a string.
(The prop is converted into a CSS property using the theme.spacing()
helper.)
Stack vs. Grid
Stack is ideal for one-dimensional layouts, while Grid is preferable when you need both vertical and horizontal arrangement.
Customization
Direction
By default, Stack arranges items vertically in a column.
Use the direction
prop to position items horizontally in a row:
Dividers
Use the divider
prop to insert an element between each child.
This works particularly well with the Divider component, as shown below:
Responsive values
You can switch the direction
or spacing
values based on the active breakpoint.
Flexbox gap
To use flexbox gap
for the spacing implementation, set the useFlexGap
prop to true.
It removes the known limitations of the default implementation that uses a CSS nested selector.
To set the prop to all stack instances, create a theme with default props:
import { CssVarsProvider, extendTheme } from '@mui/joy/styles';
import Stack from '@mui/joy/Stack';
const theme = extendTheme({
components: {
JoyStack: {
defaultProps: {
useFlexGap: true,
},
},
},
});
function App() {
return (
<CssVarsProvider theme={theme}>
<Stack>…</Stack> {/* uses flexbox gap by default */}
</CssVarsProvider>
);
}
System props
Limitations
Margin on the children
Customizing the margin on the children is not supported by default.
For instance, the top-margin on the Button
component below will be ignored.
<Stack>
<Button sx={{ marginTop: '30px' }}>...</Button>
</Stack>
white-space: nowrap
The initial setting on flex items is min-width: auto
.
This causes a positioning conflict when children use white-space: nowrap;
.
You can reproduce the issue with:
<Stack direction="row">
<Typography noWrap>
In order for the item to stay within the container you need to set min-width: 0
.
<Stack direction="row" sx={{ minWidth: 0 }}>
<Typography noWrap>
Truncation should be conditionally applicable on this long line of text as this is a much longer line than what the container can support.
Truncation should be conditionally applicable on this long line of text as this is a much longer line than what the container can support.
Anatomy
The Stack component is composed of a single root <div>
element:
<div class="MuiStack-root">
<!-- Stack contents -->
</div>