Chakra-UI


Padding & Margin

|

Chakra Docs

|

⦾ In Chakra UI, there are two fundamental concepts you must understand regarding spacing in layouts, which are padding and margin.
  • Padding: Padding is the space between the content of a box and its border. It's used to control the space within the component. In Chakra UI, you can control the padding using the p or padding props.
  • Margin: Margin is the space around the outside of a box. It's used to control the space or distance between different components. Similar to padding, you can control the margin using the m or margin props.

Both padding and margin can take a variety of inputs:

  • A number from the spacing scale:
    This will look up the 4th value on the spacing scale in the theme.
  • A string value:
    This will apply the string as a CSS value directly.
  • An array for responsive design:
    Here, padding will be 2 for mobile devices, 4 for tablet devices, and 6 for desktop devices.

Remember that the Box component in the examples can be replaced by any other Chakra UI component, like Button, Text, Flex, etc., because all Chakra UI components have these spacing props.

The Box component shown below can be imported as:

Examples

This Box has a padding setting of p=2

Here 4 is not pixels, but units from the Chakra UI's theme spacing scale.

This box has a padding-top of 4 units

In this case, pt stands for padding-top. You can use similar conventions for padding-right (pr), padding-bottom (pb), padding-left (pl), and for both x-axis and y-axis simultaneously (px, py).

This Box has a margin setting of m=4

Margin works just like padding.

This box has a margin-top of 4 units

Here, mt stands for margin-top. Similar to padding, you can also use margin-right (mr), margin-bottom (mb), margin-left (ml), and for both x-axis and y-axis simultaneously (mx, my ).

Did you know?

Creative Idea No. 1

Negative margins for overlapping elements: In Chakra UI, you can use negative margin values to create overlapping elements. This can be useful when you want to create unique visual effects or adjust the positioning of elements.

Code

Creative Idea No. 2

Responsive padding and margin values: Chakra UI provides responsive variants for padding (p) and margin (m) properties, allowing you to specify different values for different screen sizes. The responsive variants are denoted using the @ symbol.
Responsive Padding and Margin

Code

Creative Idea No. 3

Combining padding and margin shorthand: Chakra UI supports shorthand notations for setting multiple padding (p) and margin (m) values at once. You can use these shorthand notations to specify different values for individual sides of an element
Padding and Margin Shorthand

Code

copyright © 2023 IHeartComponents | evanmarie.com

Chakra-UIRemix

Special thanks to Stefan Bohacek / Generative Placeholders.