Creating the Stack layout primitive component using Styled System

Share this video with your friends

Send Tweet

In this lesson we’ll create the fourth layout primitive component — Stack, that will allow us (together with the Box, Flex and Grid components from the previous lesson) to create almost any complex layout without writing any custom CSS. We’ll use Styled System to create this component.

Stack component is a layout primitive to create stacking — adding equal spacing between each child of a container, and it’s one of the most useful layout primitives. Stack is based on the Box component, and adds spacing between the container children.

We can use it like this:

<Stack gap={3}>
  <Box>eins</Box>
  <Box>zwei</Box>
  <Box>polizei</Box>
</Stack>

This will create three <div>s stacked one on top of the other with a 8 pixels (third step in our spacing scale) gap.

The implementation is based on the lobotomized owl CSS selector:

.stack * + * {
  margin-top: 8px;
}

Here we’re adding a top margin to each container child except the first one, so we’re creating whitespace between the children but not around the container.

To define the gap prop — the spacing between the container children — we'll use the system function from styled-system, that allows us to create custom props.

The Stack implementation in this lesson is slightly simplified one, have a look at a more flexible Stack component that supports vertical and horizontal stacking, and switching direction based on the viewport width.

We’ll use following libraries:

You can either use this lesson’s Git repository or install them manually in your project:

npm install styled-components styled-system

Useful links and documentation: