Box is a component primitive that can be used to build the foundation of pretty much any other component. It keeps details like spacing, borders and colors consistent with the rest of Gestalt, while allowing the developer to focus on the content.

also known as <div>, View

Figma:

Web:

iOS:

Android:

A11y:

Props

Component props
Name
Type
Default
alignContent
"start" | "end" | "center" | "between" | "around" | "evenly" | "stretch"
"stretch"

Aligns a flex container's lines within when there is extra space in the cross-axis, similar to how justify-content aligns individual items within the main-axis.

Learn more about Flexbox layouts on MDN. If you're using Box strictly for Flexbox layouts, check out Flex!

alignItems
"start" | "end" | "center" | "baseline" | "stretch"
"stretch"

Defines the default behaviour for how flex items are laid out along the cross-axis on the current line. Think of it as the justify-content version for the cross-axis (perpendicular to the main-axis).

Learn more about Flexbox layouts on MDN. If you're using Box strictly for Flexbox layouts, check out Flex!

Also available in responsive sizes: smAlignItems, mdAlignItems, lgAlignItems. See the Screen size page to learn more about viewport breakpoints in web.

alignSelf
"auto" | "start" | "end" | "center" | "baseline" | "stretch"
"stretch"

Allows the default alignment (or the one specified by align-items) to be overridden for individual flex items.

Learn more about Flexbox layouts on MDN. If you're using Box strictly for Flexbox layouts, check out Flex!

as
"article"
| "aside"
| "caption"
| "details"
| "div"
| "figcaption"
| "figure"
| "footer"
| "header"
| "main"
| "nav"
| "section"
| "summary"
"div"

Changes the underlying DOM element when needed for accessibility or SEO reasons. Note that currently only block-level elements are available.

borderStyle
"sm" | "lg" | "shadow" | "raisedTopShadow" | "raisedBottomShadow" | "none"
"none"

Specify a border style for the box. For sizes, "sm" is 1px and "lg" is 2px. Setting a size will always default the border style to solid and color to lightGray. See the borders variant for more details.

bottom
boolean
false

Helper to specify location when using absolute positioning. See the absolute positioning variant for more info.

children
React.Node
-
color
"darkWash"
| "lightWash"
| "transparent"
| "transparentDarkGray"
| "default"
| "infoBase"
| "infoWeak"
| "errorBase"
| "errorWeak"
| "warningBase"
| "warningWeak"
| "successBase"
| "successWeak"
| "recommendationBase"
| "recommendationWeak"
| "shopping"
| "primary"
| "secondary"
| "tertiary"
| "selected"
| "inverse"
| "brand"
| "education"
| "elevationAccent"
| "elevationFloating"
| "elevationRaised"
| "dark"
| "light"
"transparent"

See the color variant for more info.

column
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12
-

See the column layout variant for more info.

Also available in responsive sizes: smColumn, mdColumn, lgColumn

dangerouslySetInlineStyle
{|
  __style: { [key: string]: string | number | void },
|}
-

An "escape hatch" used to apply styles not otherwise available on Box.

direction
"row" | "column"
"row"

Establishes the main-axis, thus defining the direction flex items are placed in the flex container.

Learn more about Flexbox layouts on MDN. If you're using Box strictly for Flexbox layouts, check out Flex!

Also available in responsive sizes: smDirection, mdDirection, lgDirection

display
"none" | "flex" | "block" | "inlineBlock" | "visuallyHidden"
"block"

The display style. See the Accessibility guidelines to learn more about using `visuallyHidden`.

Also available in responsive sizes: smDisplay, mdDisplay, lgDisplay

fit
boolean
false

Sets the max-width of the Box to 100%. See the sizing variant for more info.

flex
"grow" | "shrink" | "none"
"shrink"

Defines how a flex item will be sized. "grow", equivalent to "flex: 1 1 auto", will size the Box relative to its parent, growing and shrinking based on available space. "shrink", equivalent to "flex: 0 1 auto" (the browser default), allows the Box to shrink if compressed but not grow if given extra space. Finally, "none", equivalent to "flex: 0 0 auto", preserves the Box's size based on child content regardless of its container's size.

Learn more about Flexbox layouts on MDN. If you're using Box strictly for Flexbox layouts, check out Flex!

height
number | string
-

Use numbers for pixels: height={100} and strings for percentages: height="100%". See the sizing variant for more info.

justifyContent
"start" | "end" | "center" | "between" | "around" | "evenly"
"start"

Defines the alignment along the main axis. It helps distribute extra free space left over when either all the flex items on a line are inflexible, or are flexible but have reached their maximum size. It also exerts some control over the alignment of items when they overflow the line.

Learn more about Flexbox layouts on MDN. If you're using Box strictly for Flexbox layouts, check out Flex!

left
boolean
false

Helper to specify location when using absolute positioning. See the absolute positioning variant for more info.

lgAlignItems
"start" | "end" | "center" | "baseline" | "stretch"
-

The alignItems style in lg or larger viewports. See the Screen size page to learn more about viewport breakpoints in web.

margin
-12
| -11
| -10
| -9
| -8
| -7
| -6
| -5
| -4
| -3
| -2
| -1
| 0
| 1
| 2
| 3
| 4
| 5
| 6
| 7
| 8
| 9
| 10
| 11
| 12
| "auto"
0

Scale is in 4px increments so a margin of 2 is 8px.

Also available in responsive sizes: smMargin, mdMargin, lgMargin

marginBottom
-12
| -11
| -10
| -9
| -8
| -7
| -6
| -5
| -4
| -3
| -2
| -1
| 0
| 1
| 2
| 3
| 4
| 5
| 6
| 7
| 8
| 9
| 10
| 11
| 12
| "auto"
0

Scale is in 4px increments so a marginBottom of 2 is 8px.

Also available in responsive sizes: smMarginBottom, mdMarginBottom, lgMarginBottom

marginEnd
-12
| -11
| -10
| -9
| -8
| -7
| -6
| -5
| -4
| -3
| -2
| -1
| 0
| 1
| 2
| 3
| 4
| 5
| 6
| 7
| 8
| 9
| 10
| 11
| 12
| "auto"
0

Applies margin to the right in left-to-right languages, and to the left in right-to-left languages. See the Localization guidelines to learn more about using marginEnd.
Scale is in 4px increments so a marginEnd of 2 is 8px.

Also available in responsive sizes: smMarginEnd, mdMarginEnd, lgMarginEnd

marginStart
-12
| -11
| -10
| -9
| -8
| -7
| -6
| -5
| -4
| -3
| -2
| -1
| 0
| 1
| 2
| 3
| 4
| 5
| 6
| 7
| 8
| 9
| 10
| 11
| 12
| "auto"
0

Applies margin to the left in left-to-right languages, and to the right in right-to-left languages. See the Localization guidelines to learn more about using marginStart.
Scale is in 4px increments so a marginStart of 2 is 8px.

Also available in responsive sizes: smMarginStart, mdMarginStart, lgMarginStart

marginTop
-12
| -11
| -10
| -9
| -8
| -7
| -6
| -5
| -4
| -3
| -2
| -1
| 0
| 1
| 2
| 3
| 4
| 5
| 6
| 7
| 8
| 9
| 10
| 11
| 12
| "auto"
0

Scale is in 4px increments so a marginTop of 2 is 8px.

Also available in responsive sizes: smMarginTop, mdMarginTop, lgMarginTop

maxHeight
number | string
-

Use numbers for pixels: maxHeight={100} and strings for percentages: maxHeight="100%". See the sizing variant for more info.

maxWidth
number | string
-

Use numbers for pixels: maxWidth={100} and strings for percentages: maxWidth="100%". See the sizing variant for more info.

mdAlignItems
"start" | "end" | "center" | "baseline" | "stretch"
-

The alignItems style in md or larger viewports. See the Screen size page to learn more about viewport breakpoints in web.

minHeight
number | string
-

Use numbers for pixels: minHeight={100} and strings for percentages: minHeight="100%". See the sizing variant for more info.

minWidth
number | string
-

Use numbers for pixels: minWidth={100} and strings for percentages: minWidth="100%". See the sizing variant for more info.

opacity
0 | 0.1 | 0.2 | 0.3 | 0.4 | 0.5 | 0.6 | 0.7 | 0.8 | 0.9 | 1
-

See the opacity variant for more info.

overflow
"visible" | "hidden" | "scroll" | "scrollX" | "scrollY" | "auto"
"visible"

See the overflow variant for more info.

padding
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12
0

Supports 3 responsive breakpoints: sm, md, lg. Each sets the padding from that breakpoint and up. See the responsive padding variant for more info.

Also available in responsive sizes: smPadding, mdPadding, lgPadding

paddingX
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12
0

Horizontal padding (left/right).

Also available in responsive sizes: smPaddingX, mdPaddingX, lgPaddingX

paddingY
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12
0

Vertical padding (top/bottom).

Also available in responsive sizes: smPaddingY, mdPaddingY, lgPaddingY

position
"static" | "absolute" | "relative" | "fixed"
"static"

See the absolute positioning variant for more info.

ref
HTMLDivElement
| React.Element<"article">
| React.Element<"aside">
| React.Element<"details">
| React.Element<"figcaption">
| React.Element<"figure">
| React.Element<"footer">
| React.Element<"header">
| React.Element<"main">
| React.Element<"nav">
| React.Element<"section">
| React.Element<"summary">
-

Ref that is forwarded to the underlying input element. See the using as a ref variant for more info.

right
boolean
false

Helper to specify location when using absolute positioning. See the absolute positioning variant for more info.

role
string
-

Used to designate the Box as a type of element or landmark using ARIA roles. See the Accessibility guidelines to learn more about using role.

rounding
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | "circle" | "pill"
-

See the rounding variant for more info.

smAlignItems
"start" | "end" | "center" | "baseline" | "stretch"
-

The alignItems style in sm or larger viewports. See the Screen size page to learn more about viewport breakpoints in web.

top
boolean
false

Helper to specify location when using absolute positioning. See the absolute positioning variant for more info.

userSelect
"auto" | "none"
"auto"

Controls whether or not user can select text.

width
number | string
-

Use numbers for pixels: width={100} and strings for percentages: width="100%". See the sizing variant for more info.

wrap
boolean
false

By default, flex items will all try to fit onto one line. You can change that and allow the items to wrap onto multiple lines, from top to bottom.

Learn more about Flexbox layouts on MDN. If you're using Box strictly for Flexbox layouts, check out Flex!

zIndex
Indexable
-

An object representing the zIndex value of the Box. See the Z-Index variant for more info.

Best practices

Do

Use Box as a building block when creating other components or layouts that do not rely on flexbox. The included properties should cover any variations needed to create a diverse range of options.

If you find yourself using Box for flexbox layouts, consider Flex instead.

Don't

Don’t use the onClick, className and style properties.

Box is a pass-through component, meaning that any other properties you provide to it will be directly applied to the underlying <div>. The above properties are exceptions, however. We don’t allow onClick for accessibility reasons, so consider a Button or TapArea instead. We remove className and style to ensure style encapsulation. If necessary, dangerouslySetInlineStyle can be used to supply a style not supported by Box props.

If you need to use these features for animation purposes, use a <div> instead.

Do

When addressing the spacing of the Box, use padding before you use margins, as padding will compose better and won't collapse. Padding is applied in 4px increments and is always symmetric. Learn more about margin collapsing.

Don't

Avoid using arbitrary <div> elements. Instead, when building a component, prioritize using Box. If you need to set a custom style, you can do so using the dangerouslySetInlineStyle prop. However, this should be avoided whenever possible by utilizing the other props provided in Box. We provide a lint rule to prevent this from happening.

Accessibility

The visuallyHidden option of the display property can be used to prevent content from being visible while ensuring that screen readers still have access to the content. This can be useful when adding context for screen reader users, such as adding a pause to the labels of Checkboxes.

Visually hidden content

Setting display="visuallyHidden" on Box allows for an element to be visually hidden but still be read by screen readers.

import { Text, Box, Flex } from 'gestalt';

export default function Example() {
  return (
    <Flex
      height="100%"
      width="100%"
      justifyContent="center"
      alignItems="center"
    >
      <Text>Enable your screen reader to hear the following text:</Text>
      <Box display="visuallyHidden">Hi there.</Box>
    </Flex>
  );
}

Using 'as' property

By default, the Box component renders a div element, which is a non-semantic element that doesn't provide much meaning to the user or assistive technology. Use the as prop to inform which semantic HTML element should be rendered by the Box component instead of a div to ensure a more meaningful experience for both the user and the browser.

When using a Box component as a custom element, it is your responsibility to address all the accessibility implications. Both the role and as properties semantically classify the Box; however, the as prop defines a more concise way to describe the HTML element by modifying the underlying DOM element directly, which helps support both accessibility and SEO. Use the as prop whenever possible, making sure that the prop type is semantically associated with the Box content.

Review the available options for the as prop. For some of the options, like nav, you will also need to specify a title to ensure unique landmarks on the page. Learn more about semantics in HTML.

import { Text, Box, Flex, Heading } from 'gestalt';

export default function Example() {
  return (
    <Flex
      direction="column"
      flex="grow"
      alignItems="center"
      height="100%"
      width="100%"
    >
      <Flex height="100%" width="100%">
        <Box
          as="nav"
          title="as prop example nav"
          column={6}
          color="successBase"
          width="100%"
          padding={2}
          borderStyle="sm"
        >
          <Text color="light" weight="bold">
            Top Nav Menu: as=&quot;nav&quot;
          </Text>
        </Box>
        <Box column={6} display="inlineBlock" borderStyle="sm">
          <Box width="100%" padding={2}>
            <Text>HTML output:</Text>
            <Text>{'<nav>Menu</nav>'}</Text>
          </Box>
        </Box>
      </Flex>
      <Flex height="100%" width="100%">
        <Box
          as="article"
          column={6}
          color="successBase"
          width="100%"
          padding={2}
          borderStyle="sm"
        >
          <Heading color="light" size="500">
            Article 1
          </Heading>
          <Text color="light" weight="bold">
            Article: as=&quot;article&quot;
          </Text>
        </Box>
        <Box column={6} display="inlineBlock" borderStyle="sm">
          <Box width="100%" padding={2}>
            <Text>HTML output:</Text>
            <Text>{'<article>'}</Text>
            <Text>{'<h2>Article 1</h2>'}</Text>
            <Text>{'</article>'}</Text>
          </Box>
        </Box>
      </Flex>
    </Flex>
  );
}

Using 'role' property

Setting the role property on Box classifies the Box as the semantically appropriate HTML element through the use of an ARIA role while leaving the underlying element as a div. For example, setting role="banner" will designate that Box to be the equivalent of a <header> within the page hierarchy, allowing assistive technology to classify the Box appropriately.

Using the role property creates more specific element classification and gives the user better context on the layout of the page, especially when the ability to specify the 'as' property is not available. Learn more about ARIA roles.

import { Text, Box, Flex } from 'gestalt';

export default function Example() {
  return (
    <Flex alignItems="center" height="100%" width="100%">
      <Box column={12}>
        <Box role="feed" color="infoBase" width="100%" padding={2}>
          <Text color="light" weight="bold">
            Container: role=&quot;feed&quot;
          </Text>
          <Box column={8} display="inlineBlock">
            <Box
              role="article"
              title="Article 1"
              color="successBase"
              height={50}
              width="100%"
              padding={2}
            >
              <Text color="light" weight="bold">
                Content: role=&quot;article&quot;
              </Text>
            </Box>
          </Box>
          <Box column={4} display="inlineBlock">
            <Box
              role="form"
              color="warningBase"
              height={50}
              width="100%"
              padding={2}
            >
              <Text color="light" weight="bold">
                Contact Form: role=&quot;form&quot;
              </Text>
            </Box>
          </Box>
        </Box>
        <Box
          role="navigation"
          title="Site Map"
          color="successBase"
          height={50}
          width="100%"
          padding={2}
        >
          <Text color="light" weight="bold">
            Site Map: role=&quot;navigation&quot;
          </Text>
        </Box>
        <Text>{'Everything above will render as a <div>'}</Text>
      </Box>
    </Flex>
  );
}

Localization

Utilizing the marginStart and marginEnd properties will account for right-to-left languages and maintain proper spacing.

Page direction

Some languages (ex. Arabic, Hebrew) read from right to left (RTL) instead of from left to right. For this reason, we use marginStart and marginEnd (as opposed to left and right options) to support RTL. If specific left and right options are needed, use dangerouslySetInlineStyle.

marginStart is a left margin that flips to a right margin in a RTL layout.

marginEnd is a right margin that flips to a left margin in a RTL layout.

You can toggle the page direction using the button below to see this behavior.

import { Text, Box, Flex, Button } from 'gestalt';

function BoxWithMargins({ marginEnd = 0, marginStart = 0 }) {
  return (
    <Box
      dangerouslySetInlineStyle={{
        __style: { backgroundColor: 'rgba(110, 15, 60, 0.2)' },
      }}
    >
      <Box
        width={200}
        padding={2}
        marginEnd={marginEnd}
        marginStart={marginStart}
        dangerouslySetInlineStyle={{
          __style: { backgroundColor: 'rgba(19, 58, 94, 0.2)' },
        }}
      >
        <Text>
          {JSON.stringify(
            `marginEnd: ${marginEnd}, marginStart: ${marginStart}`
          )}
        </Text>
      </Box>
    </Box>
  );
}

export default function Example() {
  return (
    <Flex
      direction="column"
      gap={2}
      height="100%"
      alignItems="center"
      justifyContent="center"
    >
      <Button
        size="sm"
        onClick={() => {
          if (document.documentElement) {
            const isRTL = document.documentElement.dir === 'rtl';
            document.documentElement.dir = isRTL ? 'ltr' : 'rtl';
          }
        }}
        text="Toggle Page Direction"
      />

      <BoxWithMargins marginStart={8} />
      <BoxWithMargins marginEnd={8} />
      <BoxWithMargins marginStart={-8} />
      <BoxWithMargins marginEnd={-8} />
    </Flex>
  );
}

Variants

Borders

Borders are controlled by the borderStyle property. Specifying a size (sm or lg) enables a solid, light gray color in that width. Specifying shadow adds an even box-shadow around the entire container, while raisedTopShadow and raisedBottomShadow add shadows to indicate an elevated header or footer. See the elevation foundations page for more details.

borderStyle="sm"
borderStyle="lg"
borderStyle="shadow"
borderStyle="raisedTopShadow"
borderStyle="raisedBottomShadow"

Colors

The following values can be used to change the background color of Box. Be sure to use the value that semantically matches your use case. For full details on how to use our colors, visit our Color usage page.

Colors should be used semantically whenever possible (i.e. using "errorBase" for error scenarios). If a color is needed for a branded moment in product, Box color can be set using our color palette design tokens, but it is considered a hack and should be avoided.

color="default"
color="infoBase"
color="infoWeak"
color="errorBase"
color="errorWeak"
color="warningBase"
color="warningWeak"
color="successBase"
color="successWeak"
color="shopping"
color="primary"
color="secondary"
color="tertiary"
color="selected"
color="inverse"
color="brand"
color="education"
color="light"
color="dark"
color="transparent"
color="transparentDarkGray"
color="lightWash"
color="darkWash"

Elevation

Colors and shadows can elevate elements within the UI. In light mode, elevationAccent can be used when shadows or borders are not an option. elevationFloating and elevationRaised are only applicable in dark mode, while shadow is only applicable in light mode. For full details, visit our Elevation foundations page.

Color
Light mode
Dark mode
color="elevationAccent"
Light mode
Dark mode
color="elevationFloating"
Light mode
Dark mode
color="elevationRaised"
Borders and Shadows
Light mode
Dark mode
borderStyle="shadow"
Light mode
Dark mode
borderStyle="raisedTopShadow"
Light mode
Dark mode
borderStyle="raisedBottomShadow"

Rounding

The rounding property sets a border radius for the Box. Options are circle or pill for fully rounded corners or 0-8 representing the radius in 4px increments.

rounding="pill"
rounding="circle"
rounding={0}
rounding={1}
rounding={2}
rounding={3}
rounding={4}
rounding={5}
rounding={6}
rounding={7}
rounding={8}

Opacity

While we offer the full range of opacity options, below are usage guidelines for different values. See the opacity design tokens.

  • 3% (0.03): Use for Pin wash. Permanent overlay used on Pin images to ensure a visual separation between the white background and any Pin images that have pure white peripheries. For the time being, iOS uses 4%, but this will be reevaluated in the near future.
    • Note: at the moment, this can only be accomplished using the $opacity-100 token as an inline style on Box
  • 20% (0.2): Overlay wash to be used sparingly. Only use it in situations where a high-level of opacity is needed and if the 40% doesn't fit the design goal.
  • 40% (0.4): Overlay wash to supply a mid-range wash over an item (e.g. #FFFFFF media controls | #000000 wash behind modals, wash on images with text overlays).
  • 80% (0.8): Overlay wash used on most surface's scrims. Used to supply a low-level of opacity over an element (e.g. #FFFFFF image overlay | #00000 Board cover overlay) .
  • 90% (0.9): Component wash applied on IconButton and other elements as needed (e.g. image overlays). In dark mode we recommend an inverse wash. For example: Use $color-background-wash-light instead of $color-background-wash-dark.
opacity={0}
opacity={0.1}
opacity={0.2}
opacity={0.3}
opacity={0.4}
opacity={0.5}
opacity={0.6}
opacity={0.7}
opacity={0.8}
opacity={0.9}
opacity={1}

Column layout

The column property allows for automatic widths based on a 12-column grid. To create responsive layouts, specify different values for smColumn, mdColumn, and lgColumn.

column={0}
column={1}
column={2}
column={3}
column={4}
column={5}
column={6}
column={7}
column={8}
column={9}
column={10}
column={11}
column={12}

Sizing

Box can also be sized using a mixture of width, height, max/min width, max/min height, and fit.

When setting the size of a Box, the overflow property may need to be set in order to hide or scroll content that is outside the bounds of the Box.

import { Text, Box, Flex } from 'gestalt';

export default function Example() {
  return (
    <Flex height="100%" alignItems="center">
      <Box column={12}>
        <Box
          width="25%"
          minHeight={25}
          maxHeight={100}
          overflow="hidden"
          padding={2}
          borderStyle="lg"
          color="warningBase"
        >
          <Text color="light">
            Add or remove text in the editor to see the min and max heights take
            affect.
          </Text>
        </Box>
        <Box
          width="50%"
          height={100}
          padding={2}
          borderStyle="lg"
          color="successBase"
        >
          <Text color="light">
            Width and Height can be specified with numbers for &quot;px&quot;
            values or percentages
          </Text>
        </Box>
        <Box
          width="75%"
          minWidth={100}
          maxWidth={500}
          padding={2}
          borderStyle="lg"
          color="infoBase"
        >
          <Text color="light">
            Change the screen width to see the min and max widths take affect{' '}
          </Text>
        </Box>
        <Box fit padding={2} borderStyle="lg" color="errorBase">
          <Text color="light">&quot;fit&quot; sets width to 100% </Text>
        </Box>
      </Box>
    </Flex>
  );
}

Overflow

When content overflows the bounds of Box, there are multiple options to control the overflow behavior. The default is overflow="visible", but the most common use case is supplying overflow="auto" to ensure overflow content can be accessed. Learn more about CSS overflow.

import { Text, Box, Flex } from 'gestalt';

export default function Example() {
  const text =
    'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vitae nisl nec turpis vehicula ultrices. Duis pretium ut ipsum nec interdum. Vestibulum arcu dolor, consectetur ac eros a, varius commodo justo. Maecenas tincidunt neque elit, eu pretium arcu dictum ac. Donec vehicula mauris ut erat dictum, eget tempus elit luctus. In volutpat felis justo, et venenatis arcu viverra in. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Proin enim lorem, vulputate eget imperdiet nec, dapibus sed diam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Suspendisse rhoncus ut leo non gravida. Nulla tincidunt tellus sit amet ornare venenatis. Sed quis lorem cursus, porttitor tellus sed, commodo ex. Praesent blandit pretium faucibus. Aenean orci tellus, vulputate id sapien sit amet, porta fermentum quam. Praesent sem risus, tristique sit amet pulvinar in, scelerisque sit amet massa.';

  return (
    <Flex
      gap={4}
      wrap
      width="100%"
      height="100%"
      justifyContent="center"
      alignItems="center"
    >
      <Flex gap={{ column: 8, row: 0 }} direction="column" wrap>
        <Box>
          <Text>Overflow Hidden</Text>
          <Box
            overflow="hidden"
            width={300}
            maxHeight={100}
            padding={2}
            borderStyle="lg"
          >
            <Text>{text}</Text>
          </Box>
        </Box>
        <Box>
          <Text>Overflow Scroll</Text>
          <Box
            overflow="scroll"
            width={300}
            maxHeight={100}
            padding={2}
            borderStyle="lg"
            tabIndex={0}
          >
            <Text>{text}</Text>
          </Box>
        </Box>
        <Box marginBottom={4}>
          <Text>Overflow Visible</Text>
          <Box
            overflow="visible"
            width={300}
            maxHeight={100}
            padding={2}
            borderStyle="lg"
          >
            <Text>{text.substring(0, 180)}</Text>
          </Box>
        </Box>
        <Box>
          <Text>Overflow Auto</Text>
          <Box
            overflow="auto"
            width={300}
            maxHeight={100}
            padding={2}
            color="selected"
          >
            <Box width={350} padding={2} color="default" tabIndex={0}>
              <Text>{text}</Text>
            </Box>
          </Box>
        </Box>
        <Box>
          <Text>Overflow scrollX</Text>
          <Box
            overflow="scrollX"
            width={300}
            maxHeight={100}
            padding={2}
            color="selected"
          >
            <Box width={350} padding={2} color="default" tabIndex={0}>
              <Text>{text}</Text>
            </Box>
          </Box>
        </Box>
        <Box>
          <Text>Overflow scrollY</Text>
          <Box
            overflow="scrollY"
            width={300}
            maxHeight={100}
            padding={2}
            color="selected"
          >
            <Box width={350} padding={2} color="default" tabIndex={0}>
              <Text>{text}</Text>
            </Box>
          </Box>
        </Box>
      </Flex>
    </Flex>
  );
}

Responsive padding

Control the padding on different screen sizes by setting the smPadding, mdPadding or lgPadding properties. In the example, we increase the padding for every breakpoint in either all directions, the x-axis only or the y-axis only.

import { Box, Flex } from 'gestalt';

export default function Example() {
  return (
    <Flex
      gap={{ column: 0, row: 3 }}
      height="100%"
      width="100%"
      alignItems="center"
      justifyContent="center"
    >
      <Box
        padding={0}
        smPadding={1}
        mdPadding={4}
        lgPadding={8}
        color="darkWash"
      >
        <Box width={40} height={40} color="successBase" />
      </Box>
      <Box
        paddingX={0}
        smPaddingX={1}
        mdPaddingX={4}
        lgPaddingX={8}
        color="darkWash"
      >
        <Box width={40} height={40} color="infoBase" />
      </Box>
      <Box
        paddingY={0}
        smPaddingY={1}
        mdPaddingY={4}
        lgPaddingY={8}
        color="darkWash"
      >
        <Box width={40} height={40} color="warningBase" />
      </Box>
    </Flex>
  );
}

Auto margins

Auto margin is a useful tool when positioning items without using flexbox layouts. By setting any of the margin properties to "auto", the margin will extend to fill the extra space.

This can be seen below, where the 5-column width Box is centered using margin="auto" and the 3-column width Box uses marginStart="auto" to automatically adjust the Box to the far edge.

import { Box, Flex } from 'gestalt';

export default function Example() {
  return (
    <Flex justifyContent="center" height="100%" width="100%">
      <Box color="infoBase" marginStart={12} marginEnd={12} column={12}>
        <Box
          borderStyle="sm"
          color="successBase"
          margin="auto"
          column={5}
          height={100}
        />
        <Box
          borderStyle="sm"
          color="warningBase"
          marginStart="auto"
          column={3}
          height={100}
        />
      </Box>
    </Flex>
  );
}

Absolute positioning

Position is static by default but can be made absolute. Box has helpers to help align to absolute edges (top, bottom, left, right). These can be used in combination with padding to achieve desired offsets from edges.

import { Text, Box } from 'gestalt';

export default function Example() {
  return (
    <Box height="100%" width="100%">
      <Box position="absolute" top left padding={2} color="infoBase">
        <Text color="light">Top Left</Text>
      </Box>
      <Box position="absolute" top right padding={2} color="infoBase">
        <Text color="light">Top Right</Text>
      </Box>
      <Box position="absolute" bottom left padding={2} color="infoBase">
        <Text color="light">Bottom Left</Text>
      </Box>
      <Box position="absolute" bottom right padding={2} color="infoBase">
        <Text color="light">Bottom Right</Text>
      </Box>
    </Box>
  );
}

Using as a ref

The ref property can be used to anchor a Popover to a Box.

import { Fragment, useState, useRef } from 'react';
import { Text, Box, Flex, Button, Popover } from 'gestalt';

export default function Example() {
  const [open, setOpen] = useState(false);

  const anchorRef = useRef(null);

  return (
    <Fragment>
      <Flex
        direction="column"
        gap={6}
        height="100%"
        width="100%"
        justifyContent="center"
        alignItems="center"
      >
        <Button
          color="red"
          onClick={() => setOpen((prevVal) => !prevVal)}
          text={open ? 'Close Popover' : 'Anchor a Popover to Box'}
        />
        <Box borderStyle="sm" padding={3} ref={anchorRef} rounding={1}>
          <Text>I&apos;m a Box</Text>
        </Box>
      </Flex>
      {open && (
        <Popover
          anchor={anchorRef.current}
          idealDirection="down"
          onDismiss={() => {}}
          shouldFocus={false}
        >
          <Box padding={3}>
            <Text weight="bold">I&apos;m a Popover anchored to a Box</Text>
          </Box>
        </Popover>
      )}
    </Fragment>
  );
}

Z-Index

It's possible to use Box with external elements using the CSS z-index property by capturing those values in controlled objects. The example below shows using a FixedZIndex for a value that comes from somewhere else, and a CompositeZIndex to layer the Box on top of it. Visit our Z-Index documentation for more details on how to use these utility classes.

import { Text, Box, CompositeZIndex, FixedZIndex, Sticky } from 'gestalt';

export default function Example() {
  const HEADER_ZINDEX = new FixedZIndex(100);
  const zIndex = new CompositeZIndex([HEADER_ZINDEX]);
  return (
    <Box
      column={12}
      dangerouslySetInlineStyle={{ __style: { isolation: 'isolate' } }}
      height={150}
      overflow="scroll"
      tabIndex={0}
    >
      <Sticky top={0} zIndex={HEADER_ZINDEX}>
        <Box color="errorBase" width="80%" height={60} padding={2}>
          <Text color="light">
            This is sticky and won&apos;t move when scrolling
          </Text>
        </Box>
      </Sticky>
      <Box
        color="infoBase"
        width="50%"
        height={100}
        zIndex={zIndex}
        position="relative"
        padding={2}
      >
        <Text color="light">
          This will float above the sticky Box when scrolling
        </Text>
      </Box>
      <Box color="successBase" width="30%" height={120} padding={2}>
        <Text color="light">
          This will go behind the sticky Box when scrolling
        </Text>
      </Box>
    </Box>
  );
}

Component quality checklist

Component quality checklist
Quality item
Status
Status description
Figma Library
Component is not currently available in Figma.
Responsive Web
Ready
Component is available in code for web and mobile web.
iOS
Component is not currently available in code for iOS.
Android
Component is not currently available in code for Android.

Flex
Use Flex for flexbox layouts, especially when even spacing between elements is desired, by using the gap property.

Container
Use Container to responsively layout content with a max-width on large screens.

ScrollBoundaryContainer
For proper positioning when using anchored components (Popover, Tooltip, etc.) within a container that could scroll, use ScrollBoundaryContainer.

TapArea
If a tap target is needed in order to click on a portion of the page, use TapArea, since onClick is not supported on Box.

Sticky
Use Sticky if a portion of the page should stick to either the top or bottom when scrolling.