Skip to content

Responsive styles

How to use responsive styles with components

Casper UI Library supports responsive styles through Chakra UI’s styled system and its ConditionalValue-type. Instead of manually adding @media-queries and adding nested styles throughout your code, Chakra UI allows you to provide object and array values to add mobile-first responsive styles.

These examples and guidelines are based on the contents of Chakra UI Docs - Responsive Styles.

The Casper UI theme provides a set of pre defined break points in ThemeBreakPoint:

  • ThemeBreakPoint.Base = 0em / 0px
  • ThemeBreakPoint.Small = 30em / 480px
  • ThemeBreakPoint.Medium = 48em / 768px
  • ThemeBreakPoint.Large = 62em / 992px
  • ThemeBreakPoint.XLarge = 80em / 1280px
  • ThemeBreakPoint.X2Large = 96em / 1536px

To apply different styles for different breakpoints we can use an Array-syntax or an Object-syntax.

Let’s say you have a Text you want to have a different font size based on breakpoint. To make the font size responsive using the array syntax, here’s what you need to do:

import { Text, ThemeFontSize } from "@caspeco/casper-ui-library";
<Text fontSize={[ThemeFontSize.Large, ThemeFontSize.Medium, ThemeFontSize.Small]}>
Some nice text content
</Text>;

Chakra UI then converts the values defined by our breakpoints and sorts them in ascending order. Here’s how to interpret the output of this array:

Breakpoint Breakpoint value Font size
ThemeBreakPoint.Base 0em and upwards ThemeFontSize.Large
ThemeBreakPoint.Small 30em upwards ThemeFontSize.Medium
ThemeBreakPoint.Medium 48em upwards ThemeFontSize.Small

You can also define responsive values with breakpoint aliases in an object. Here’s how you would achive the font size example using the Object syntax.

import { Text, ThemeFontSize } from "@caspeco/casper-ui-library";
<Text
fontSize={{
base: ThemeFontSize.Large,
sm: ThemeFontSize.Medium,
md: ThemeFontSize.Small,
}}
>
Some nice text content
</Text>;

The output of this example will be the same as the Array-example.

Sometimes you want to skip breakpoints to avoid generating unnecessary CSS.

Pass null to any position in the array:

<Text fontSize={[ThemeFontSize.Large, null, ThemeFontSize.Small]}>Some nice text content</Text>

Only assign values to the breakpoints you want to define styles for:

<Text
fontSize={{
base: ThemeFontSize.Large,
md: ThemeFontSize.Small,
}}
>
Some nice text content
</Text>