# Style Props Deprecation Overview

### Purpose

As part of the Canvas Kit’s modernization process, we’re moving away from Emotion’s runtime styling
and promoting a custom CSS-in-JS solution: `@workday/canvas-kit-styling`. This change improves
**performance**, **consistency**, and **maintainability** across our codebase. For more information,
view our [Future of](https://github.com/Workday/canvas-kit/discussions/2265) discussion.

### Goals

- **Reduce runtime overhead** by removing Emotion’s runtime from `@emotion/react`
- **Promote prescriptive, opinionated styling** across Workday
- **Enable static CSS compilation** for faster load times and smaller bundles
- **Support new design tokens and CSS Variables** for scalable theming
- **Ensure proper style merging** and stable selector behavior
- **Support advanced styling patterns** like compound styles, modifiers, and `data-parts`

> Emotion dynamically injects styles at runtime, causing costly re-renders and cache invalidations.
> The new system statically compiles styles at build time for optimal performance.

### Timeline

- **Deprecation introduced:** Canvas Kit **v14.1**
- **Removal:** _Not immediate_ — style props and `styled()` will continue to function in upcoming
  releases
- **Migration timeline:** Gradual; no immediate codebase-wide update required

## LLM Assisted Migration <StorybookStatusIndicator type="ai" />

We've provided an **LLM migration mapping file** (`llm-style-props-migration.txt`) specifically
designed for use with LLM-based code assistants such as [Cursor](https://www.cursor.so/). It
contains a compiled LLM consumption version of this v14 Upgrade Guide. It is not intended for direct
human reference or team documentation, but rather as structured input for LLMs to automate and
assist with your migration process.

> **Important:** LLMs can make mistakes. Please verify changes using this Migration Guide.

**How to use:**

- **View raw file**: Open the file in a new tab to see the complete migration mapping
- **Download LLM File**: Save the file locally to upload or paste into your LLM/code assistant
- **Use with LLM**: Provide the raw content to your LLM/code assistant as context for automated
  migration

<DownloadLLMFile
  rawFileLink="https://raw.githubusercontent.com/Workday/canvas-kit/master/modules/docs/llm/llm-style-props-migration.txt"
  filename="llm-style-props-migration.txt"
/>

## Changes Overview

### Replacements

Use the new **Canvas Kit Styling** utilities:

| Old API                                            | New API                          | Purpose                                    |
| -------------------------------------------------- | -------------------------------- | ------------------------------------------ |
| `styled()`                                         | `createStyles` / `createStencil` | Define static or component-level styles    |
| Inline style props, like `background` or `padding` | `cs` prop                        | Safely merge class names and styles        |
| Dynamic values                                     | `createVars`                     | Manage CSS variables for runtime overrides |
| Emotion modifiers                                  | `modifiers`, `compound`          | Define consistent appearance variants      |

## Canvas Kit Styling

<InformationHighlight className="sb-unstyled" cs={{p: {marginBlock: 0}}}>
  <InformationHighlight.Icon />
  <InformationHighlight.Heading>Canvas Kit Styling Docs</InformationHighlight.Heading>
  For a detailed overview of our styling approach, view our styling docs.
  <InformationHighlight.Link href="https://workday.github.io/canvas-kit/?path=/docs/styling-getting-started-overview--docs">
    Read more
  </InformationHighlight.Link>
</InformationHighlight>

Canvas Kit’s styling utilities are built for **static CSS generation**, **token integration**, and
**predictable composition**.

### Core APIs

- **`createStyles`** — define reusable, static CSS objects.
- **`createStencil`** — define reusable, dynamic component styles with parts, vars, and modifiers
- **`cs` prop** — apply multiple styles and handle merges consistently to Canvas Kit components

### Best Practices

These best practices ensure your components remain **performant**, **consistent**, and
**maintainable** under the new Canvas Kit Styling system.

#### Define Styles Outside the Render Function

Always declare styles at the module level. Creating styles inside the render or component function
will trigger component re-render.

✅ **Do**

```tsx
// `createStyles` returns a string of className
const buttonStyles = createStyles({
  backgroundColor: system.color.bg.primary.default,
  color: system.color.text.inverse,
});

export const MyButton = () => <button className={buttonStyles}>Click me</button>;
```

❌ **Don’t**

```tsx
export const MyButton = () => {
  const buttonStyles = createStyles({backgroundColor: 'red'}); // bad
  return <button cs={buttonStyles}>Click me</button>;
};
```

#### Use `createStyles` for Static Styling

Use `createStyles` for simple, reusable style objects that do **not** depend on dynamic data or
props.

✅ Ideal for:

- Defining base styles
- Applying static overrides
- Styling tokens-based components

`createStyles` returns a string of className that can be applied to a React element. If you're
applying the class to a Canvas Kit component, you can use the `cs` prop.

```tsx
import {BaseButton} from '@workday/canvas-kit-react/button';
import {createStyles} from '@workday/canvas-kit-styling';
// `createStyles` returns a string of className
const buttonStyles = createStyles({
  backgroundColor: system.color.bg.primary.default,
  color: system.color.text.inverse,
});

export const MyButton = () => <BaseButton cs={buttonStyles}>Click me</button>;
```

#### Use `createStencil` for Dynamic or Complex Styling

Use `createStencil` when styles depend on **props**, **variants**, or **component parts**.

Examples:

- Size or color variants (`primary`, `secondary`)
- Compound state combinations (`size=small`, `iconPosition=end`)
- Multi-part components (e.g. `Button`, `Card`, `MenuItem`)

✅ **Do**

```tsx
const buttonStencil = createStencil({
  vars: {color: '', background: ''},
  base: ({color, backgroundColor}) => ({
    color: cssVar(color, system.color.text.default),
    backgroundColor: cssVar(backgroundColor, system.color.bg.default),
  }),
  modifiers: {
    variant: {
      primary: {background: system.color.bg.primary.default},
      secondary: {background: system.color.bg.muted.default},
    },
  },
});
```

- **vars**: If you initialize the variable with an empty string, it will allow the variable to
  cascade and be defined.

```tsx
const customButtonStencil = createStencil({
  base: {
    // Set the color variable to the primary color
    [buttonStencil.vars.color]: system.color.fg.primary.default,
  },
});
```

- **cssVar**: The `cssVar` function is used when you want to add a default value if the CSS Variable
  is not defined.
- **modifiers**: The `modifiers` property is used to define the styles for the different variants of
  the component.

#### Use `cs` Prop to Merge Styles

The `cs` prop merges `className` and `style` attributes safely and consistently. Use this over using
style props or className concatenation.

✅ **Do**

```tsx
<PrimaryButton cs={[baseStyles, variantStyles]} />
```

❌ **Don’t**

```tsx
<PrimaryButton className={`${baseStyles} ${variantStyles}`} />
```

#### Use Variables for Dynamic Values

Instead of inline styles or runtime calculations, use stencil variables.

✅ **Do**

```tsx
const primaryButtonStencil = createStencil({
  base: {
		// Use the buttonStencil variable to set the background color
    [buttonStencil.vars.background]: 'orange',
  }
})
<PrimaryButton cs={primaryButtonStencil} />
```

❌ **Don’t**

```tsx
<PrimaryButton cs={{backgroundColor: 'orange'}} /> // breaks static optimization
```

#### Extend Existing Stencils Instead of Overriding Styles

When modifying Canvas Kit components, extend the provided `Stencil` instead of creating your own
from scratch.

✅ **Do**

```tsx
const customIconStencil = createStencil({
  extends: systemIconStencil,
  base: {
    margin: system.space.x2,
  },
});
```

This will inherit both the styles and variables from the `systemIconStencil`.

#### Use Modifiers for Variants and States

Define component variations (size, color, emphasis) using **modifiers** rather than conditional
logic.

✅ **Do**

```tsx
const badgeStencil = createStencil({
  modifiers: {
    status: {
      success: {background: system.color.bg.success.default},
      error: {background: system.color.bg.negative.default},
    },
  },
});
```

#### Use Compound Modifiers for Complex Conditions

When two or more modifiers combine to produce a new style, define a **compound modifier**.

✅ **Do**

```tsx
const myCustomStencil = createStencil({
  base: {
    //base styles
  },
  modifiers: {
    variant: {
      primary: {
        // primary variant styles
      },
    },
    size: {
      large: {
        // large size styles
      },
    },
  },
  compound: [
    {
      // apply styles when the variant is primary AND the size is large
      modifiers: {variant: 'primary', size: 'large'},
      styles: {paddingInline: system.space.x5},
    },
  ],
});
```

#### Avoid Nested Stencils Unless Necessary

Each Stencil should map to one semantic component. Nested stencils can increase CSS specificity and
complexity. Use **parts** instead of deep nesting.

✅ **Do**

```tsx
const cardStencil = createStencil({
  parts: {header: 'card-header', body: 'card-body'},
  base: ({headerPart}) => ({
    [headerPart]: {
      fontWeight: 'bold',
    },
  }),
});

<Card cs={cardStencil}>
  <Card.Heading {...cardStencil.parts.header}>Card Title</Card.Heading>
  <Card.Body {...cardStencil.parts.body}>Card Body</Card.Body>
</Card>;
```

#### Prefer Tokens and System Variables

Always use design tokens (`system`) for spacing, colors, typography, etc., instead of raw values.
View our System Tokens
[docs](https://workday.github.io/canvas-tokens/?path=/docs/docs-system-tokens-overview--docs) for
more information.

✅ **Do**

```tsx
color: system.color.text.default;
margin: system.space.x2;
```

❌ **Don’t**

```tsx
color: '#333';
margin: '8px';
```

#### Debugging and Static Compilation

- Enable static compilation during development to catch type or value errors early.
- Use `as const` for static objects to ensure values are type-locked for the compiler.

✅ **Do**

```tsx
const reusableStyles = {
  position: 'absolute',
} as const;
```

#### Don’t Mix Emotion and Static Styling

Avoid combining Emotion’s `styled` or `css` with `createStyles` or `createStencil`. It reintroduces
runtime style recalculations and negates static benefits.

❌ **Don’t**

```tsx
const StyledButton = styled(Button)(styles);
<StyledButton cs={createStyles({padding: 8})} />;
```

## Migration Example

### Style Props

#### Before

```typescript
import {Flex} from '@workday/canvas-kit-react/layout';

<Flex depth={1} marginX={10} background="frenchVanilla100" />;
```

#### After

```typescript
import {Flex} from '@workday/canvas-kit-react/layout';
import {system} from '@workday/canvas-tokens-web';
import {px2rem} from '@workday/canvas-kit-styling';

<Flex
  cs={{
    boxShadow: system.depth[1],
    marginInline: px2rem(10),
    background: system.color.bg.default,
  }}
/>;
```

- **px2rem**: The `px2rem` function is used to convert a pixel value to a rem value.
- Use [CSS logical
  properties](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_logical_properties_and_values
- Use `system` tokens over `base` tokens for better theming support.

### Emotion styled

#### Before (Emotion)

```tsx
const StyledButton = styled('button')({
  backgroundColor: 'blue',
  color: 'white',
});
```

#### After (Canvas Kit Styling)

```tsx
import {createStyles} from '@workday/canvas-kit-styling';
import {PrimaryButton} from '@workday/canvas-kit-react/button';
import {system} from '@workday/canvas-tokens-web';

const primaryButtonStyles = createStyles({
  backgroundColor: system.color.bg.primary.default,
  color: system.color.text.inverse,
});

<PrimaryButton cs={primaryButtonStyles}>Click me</PrimaryButton>;
```

# Canvas Kit Styling

## Introduction

Canvas Kit styling is a custom CSS-in-JS solution that provides both a runtime for development and a static parsing process for build time. This system offers several key benefits:

## Why Canvas Styling

This package contains everything needed to create CSS styling. This styling package contains a runtime for development and a static parsing process for build time.

Here are the goals for this project:

- TypeScript autocomplete of CSS object properties
- Low runtime for development
- Static CSS compilation for faster user experience
- Static CSS extraction for CSS only packages
- Dynamic styles using CSS Variables

If you're using Canvas Kit and not directly using this package, there is nothing extra to do on your end. The Canvas Kit packages are using the static compilation as part of the build process. If you want to use this package for your own styles, you don't need to do anything special to use in development. Included is a small runtime to get styling working. If you wish to statically compile your CSS from your TypeScript files for faster page loading, visit the [Getting Started](/docs/styling-getting-started--docs) page.

### Why?

Canvas Kit no longer needs to support IE11 which allows us to use [CSS Custom Properties a.k.a. CSS Variables](https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties). Dynamic style properties (properties that change during the lifecylce of the component) are the most costly in terms of performance in Emotion and should be avoided. Also, any conditionals in your Emotion style functions create unique hashes in the Emotion cache and makes that render frame pay an expensive [style recalculation](https://microsoftedge.github.io/DevTools/explainers/StyleTracing/explainer.html).

We can avoid most of the cost of Emotion's runtime by using [@emotion/css](https://www.npmjs.com/package/@emotion/css) instead and hoist all style definitions outside of a component's render function. All dynamic styling can be moved into "modifiers" (from [BEM](https://getbem.com/introduction/#modifer:~:text=%2C%20header%20title-,Modifier,-A%20flag%20on)).

There's still a runtime to select which styles should apply to an element and what the CSS Variable should be, but it is essentially only having to choose what CSS classes should apply to an element and changing the `style` property to set the CSS Variables. This does not require new [StyleSheet](https://developer.mozilla.org/en-US/docs/Web/API/StyleSheet) inserts which cause expensive style recalculation. Think of the runtime as being the following:

```jsx
<div
  className={getClassNames(/* input from props */)}
  style={getCSSVarValues(/* input from props */)}
/>
```

For further information, please read our GitHub discussion on [the future of styling](https://github.com/Workday/canvas-kit/discussions/2265)

### What is Canvas Kit Styling?

Canvas Kit Styling includes two things:

1. A utility function wrapper around `@emotion/css`
2. An optional static compiler to remove most of the runtime

#### Utility Functions

This packages provides three utility functions to make it easier to style element-based components. The following is a brief description of each function. If you'd like to read a more in-depth discussion of each, our [API docs](/docs/features-styling-api--create-styles).

The primary utility function is the `createStyles` function. It makes a call to the `css` function from `@emotion/css`. Emotion still does most of the heavy lifting by handling the serialization, hashing, caching, and style injection.

The other two utility functions, `createVars` and `createModifiers`, provide supplemental styling functionality. `createVars` allows you to create temporary CSS variables within components to create dynamic properties. And `createModifiers` creates a modifier function to create dynamic groups of properties. If you're familiar with modifiers in [BEM](https://getbem.com/introduction/) (Block, Element, Modifier) CSS, you're well on your way to understanding this function's intent.

#### Static Compiler

The static compiler run as a TypeScript transform during TypeScript's transpilation phase. It requires the TypeScript type checker to determine the static value of any variables used. The transformer calls `@emotion/serialize` to pre-compute the serialized styles and hash so that `@emotion/css` can skip these steps. For example, there's the before/after of the code.

```ts
// before
const myVars = createVars('textColor', 'backgroundColor');

const myStyles = createStyles({
  fontSize: 12,
  color: cssVar(myVars.textColor),
  backgroundColor: cssVar(myVars.backgroundColor),
});

// after
const myVars = createVars('textColor', 'backgroundColor');

const myStyles = createStyles({
  name: 'a8g234',
  styles:
    'font-size: 12px; color: var(--css-my-vars-textColor); backgroundColor: var(--css-my-vars-backgroundColor);',
});
```

Emotion has an internal shortcut that recognizes the `styles` property and [short-circuits interpolation](https://github.com/emotion-js/emotion/blob/f3b268f7c52103979402da919c9c0dd3f9e0e189/packages/serialize/src/index.js#L319).

### Performance

`createStyles` is more performant than `styled` components or the `css` prop because the styles must be statically evaluated. The actual characters of a CSS property value cannot change at runtime. This means we do not need to recalculate a hash every render or inject new `StyleSheet` entries into the `StyleSheetList` in a render cycle. Injecting new `StyleSheets` causes slow [Style Recalculation](https://web.dev/articles/reduce-the-scope-and-complexity-of-style-calculations). What is not well known is browser engines maintain an internal selector cache to make style recalculations as fast as possible. Adding a CSS class to a DOM element will invoke a style recalculation, but if the the CSS selector is already in the `StyleSheetList`, the browser can optimize how those styles are applied to the current element.

In the runtime Emotion's case, a novel style will result in a new style hash which results in a new `StyleSheet` being injected into the `StyleSheetList`. To be safe, the browser's runtime engine will throw away any style recalculation cache and start from scratch. This happens if you render a new component on the page that hasn't been rendered yet, or if you make one of your style properties dynamic between render cycles. Eventually the Emotion cache gets warm and style recalcuation costs start to normalize and no longer invalidate the browser's selector cache.

On a page with over 1,000 elements and over 1,000 [CSSRules](https://developer.mozilla.org/en-US/docs/Web/API/CSSRule), (typical of a large web application), the difference between a &lt; 1ms for warmed selector cache and &gt; 100ms for a fresh selector cache. `createStyles` encourages a pattern similar to [BEM](https://getbem.com/) which works well with the browser's selector cache by not injecting new `StyleSheet`s during a page's normal operations. All styles are injected before any rendering takes place.

> **Note:** Since style props force Emotion's dynamic rendering, style props will fall back to
> Emotion's runtime performance characteristics and lose any benefits gained. Also if you use
> `styled` components or the `css` prop in a tree that uses `createStyles`, the styles created by
> the runtime APIs will still result in a selector cache invalidation. Even if you want to use
> `styled` or the `css` prop, consider using CSS Variables for dynamic CSS property values to reduce
> the performance overhead of Emotion.

## Overview

The Canvas Kit styling system consists of two main packages:

- `@workday/canvas-kit-styling` - Core styling utilities for runtime use
- `@workday/canvas-kit-styling-transform` - Build-time optimization tools

These packages work together to provide a CSS-in-JS experience during development while enabling optimized static CSS in production.

## Installation

```sh
yarn add @workday/canvas-kit-styling
```

## Usage

```tsx
import React from 'react';
import {createRoot} from 'react-dom/client';

import {createStyles} from '@workday/canvas-kit-styling';

const myStyles = createStyles({
  backgroundColor: 'red',
}); // returns the CSS class name created for this style

myStyles; // something like "css-{hash}"

const domNode = document.getElementById('root');
const root = createRoot(domNode);

root.render(<div className={myStyles}>Hello!</div>);
```

## Style Merging

The `@workday/canvas-kit-styling` package uses `@emotion/css` to inject styles during JavaScript evaluation time rather than `@emotion/react` or `@emotion/styled` injecting when a component is rendered. This means the Emotion cache needs to be known before any style is created. In order to properly merge styles with components using either dynamic styling package, the Emotion cache must be changed on any React application. Without this, styles will not be merged correctly when static and dynamic styles are used on the same element.

If you're using Canvas Kit React, you should use the `<CanvasProvider>` which includes Emotion's `<CacheProvider>` with the proper cache already set. If you're not using Canvas Kit React, you should use the `<CacheProvider>`:

```tsx
// ONLY use if not using the <CanvasProvider>
import {getCache} from '@workday/canvas-kit-styling';

// in your application bootstrap
const root = React.createRoot(document.getElementById('root'));

root.render(
  <CacheProvider value={getCache()}>
    <App />
  </CacheProvider>
);
```

## Known issues

### Hot Reloading

Style merging works by using CSS specificity rather than JavaScript runtime. This can cause problems during hot reloading. If you specify all styles in the same file, hot reloading shouldn't result in any style merging problems. But if you use `extends` in `createStencil` that references another file, you may run into style merge issues.

For example:

```ts
// base.tsx file
export const baseStencil = createStencil({
  base: {
    color: 'red',
  },
});

// extended.tsx file
import {baseStencil} from './base';

export const extendedStencil = createStencil({
  extends: baseStencil,
  base: {
    color: 'blue',
  },
});
```

This will render correctly until you change `color` in `base.tsx` and get a hot reload:

```tsx
// base.tsx file
export const baseStencil = createStencil({
  base: {
    color: 'purple',
  },
});
```

The hot reload will evaluate this update and inject a new style.

## Development

Canvas Kit Styling comes with a runtime that doesn't need anything special for development. The runtime uses `@emotion/css` to include your styles on the page. If you plan to use static compilation, we recommend enabling in production as well so you can fix static compilation errors as you develop rather than get errors only in production builds.

## Static compilation

The `@workday/canvas-kit-styling-transform` package can to pre-build styles. This process takes style objects and turns them into CSS strings. This process moves serialization and hashing to build time rather than browser runtime when `@emotion/css` is processing styles. This will speed up production builds at runtime.

Static compilation has stricter requirements than when doing runtime styling. The static compiler uses the TypeScript type system to statically analyze style values and thus requires value types to be known by TypeScript. See [Restrictions](#restrictions).

Static compilation may be required for server side rendering (SSR), especially when using React Server Components.

### Hash generation

Emotion generates hashes based on the serialized style object. This means a style should always give the same hash. Static styling hashes differently. Every `createStyles` or `createStencil` call will generate a unique hash even if the style object is the same. This is required for proper style merging because static styling doesn't give single class names, but rather merges styles using CSS specificity.

For runtime development, the hash is always unique. For static compilation, the hash is based on the start and end character count in the source file of the style block. This is required for SSR so that the server and client agree on the same value during hydration. This means that while debugging, the hash depends on any code before it. If you add a `console.log` for example, the character index of a style block could shift which will generate a new hash.

### Restrictions

The static compiler uses the TypeScript type checker. The easiest way to think of these restrictions is if TypeScript knows the exact value, the static compiler will also know. A simple example:

```ts
// won't work - `value` is a type of `string` because `let` allows a value to be mutated
let value = 'absolute'; // `string`

const myStyles = createStyles({
  position: value, // error - `string` isn't specific enough.
});

// will work - `value` is a type of `'absolute'` because `const` restricts to a string literal
const value = 'absolute'; // `'absolute'`

const myStyles = createStyles({
  position: value, // works. If you mouse over `value` in your editor, you'll see the type is `'absolute'`
});
```

More complex examples may be objects:

```ts
// won't work. TypeScript will not understand that the position will only be `'absolute'` and makes it a `string` instead
const reusableStyles = {
  position: 'absolute',
}; // `{ position: string }`

const myStyles = createStyles({
  ...reusableStyles, // error - `position` is a `string` and not specific enough
});

// will work. Adding `as const` tells TypeScript the object is readonly and therefore no values can change
const reusableStyles = {
  position: 'absolute',
} as const; // `{ readonly position: 'absolute' }`

const myStyles = createStyles({
  ...reusableStyles, // works. If you mouse over, the position is a string literal `'absolute'`
});
```

Functions are a little more tricky and may require generics.

```ts
// generic makes the type be statically knowable
function getPosition<V extends 'relative' | 'absolute'>(value: V): {position: V} {
  return {position: value};
}

// mouse over `position` in your editor an the type will be `{ position: 'absolute' }`
const position = getPosition('absolute'); // { position: 'absolute' }

const myStyles = createStyles({
  ...getPosition('absolute'), // works - `{ position: 'absolute' }`
});
```

### Webpack

The `@webpack/canvas-kit-styling-transform` package comes with a webpack loader that can be added to development and/or production.

```js
// import the transform - CJS and ESM are supported
import {StylingWebpackPlugin} from '@workday/canvas-kit-styling-transform';

// somewhere only once. For static webpack config files, this can be near the top.
// If inside Storybook, Gatsby, Next.js, etc configs, put inside the function that is called that
// returns a webpack config
const tsPlugin = const tsPlugin = new StylingWebpackPlugin({
  tsconfigPath: path.resolve(__dirname, '../tsconfig.json'), // allows your TS config to be used
  // A different tsconfig could be used if you want to use TS to transpile to something like ES2019 and
  // also have Babel process the file.
});

// However you need to define rules.
// This is different for using webpack directly or in Storybook/Gatsby/Next.js/etc
{
  rules: [
    //...
    {
      test: /.\.tsx?$/,
      use: [
        {
          loader: require.resolve('@workday/canvas-kit-styling-transform/webpack-loader'),
          options: tsPlugin.getLoaderOptions(),
        },
      ],
      enforce: 'pre'
    },
  ];
  // We need to pass the plugin to Webpack's plugin list. Failure to do this will result in a
  // production build hanging
  plugins: [tsPlugin]
}
```

## Core Styling Approaches for Static Styling

For proper static styling there's two methods that you can use to apply styles.

1. Using `createStyles` for simple object base styles.
2. Using `createStencil` for dynamic styles and reusable components.

Both approaches are intended to be used in tandem with the `cs` prop when applying styles to our components.

### `cs` Prop

The `cs` prop takes in a single, or an array of values that are created by the `cs` function, a string representing a CSS class name, or the return of the `createVars` function. It merges everything together and applies `className` and `style` attributes to a React element. Most of our components extend the `cs` prop so that you can statically apply styles to them.

> **Important**: While the `cs` prop accepts a style object, **this will not** be considered
> statically styling an element and you will lose the performance benefits. We plan on providing a
> babel plugin to extract these styles statically in a future version.

```tsx
import {system} from '@workday/canvas-tokens-web';
import {PrimaryButton} from '@workday/canvas-kit-react/button';

const styles = createStyles({color: system.color.static.red.default});

function MyComponent() {
  return <PrimaryButton cs={styles}>Text</PrimaryButton>;
}
```

### `createStyles`

The primary utility function is the `createStyles` function. It makes a call to the `css` function from `@emotion/css`. Emotion still does most of the heavy lifting by handling the serialization, hashing, caching, and style injection.

In this example, the HTML will look like:

```html
<div class="css-m39zwu"></div>
```

The CSS will look like this:

```css
.css-m39zwu {
  background: var(--cnvs-sys-color-bg-primary-default);
  color: var(--cnvs-sys-color-text-inverse);
}
```

> Note:
> The `createStyles` function handles wrapping our Tokens in `var(--tokenName)`.

We're using `className` for simplicity here.

```ts
const styles = createStyles({
  background: system.color.bg.primary.default,
  color: system.color.text.inverse,
});

export const CreateStyles = () => {
  return <button className={styles}>Click Me</button>;
};
```

> Caution: Performance Hit
> Do not inline the call to `createStyles` in the render function of a component. 
> This will cause performance issues as a new style is inserted into the browser on every render.

```tsx
// Bad example (inside render function)
import {system} from '@workday/canvas-tokens-web';
import {PrimaryButton} from '@workday/canvas-kit-react/button';

function MyComponent() {
  const styles = createStyles({color: system.color.static.red.default}); // Don't do this
  return <PrimaryButton className={createStyles({color: system.color.static.red.default})}>Text</PrimaryButton>;
}
```

#### When to Use `createStyles`

`createStyles` is a great way to generate static styles when styling our components that don't rely on dynamic styles. Use `createStyles` if you want to create re useable styles or need to apply simple style overrides to our components.

#### When to Use Something Else

You should use [stencils](/docs/styling-getting-started-stencils--docs) when styling our components that have complex styles and dynamic properties.

#### Proper Usage

```tsx
// Bad example (inside render function)
import {system} from '@workday/canvas-tokens-web';
import {PrimaryButton} from '@workday/canvas-kit-react/button';

function MyComponent() {
  const styles = createStyles({color: system.color.static.red.default}); // Don't do this
  return <PrimaryButton cs={styles}>Text</PrimaryButton>;
}

// Good example (outside render function)
import {system} from '@workday/canvas-tokens-web';
import {PrimaryButton} from '@workday/canvas-kit-react/button';

const styles = createStyles({color: system.color.static.red.default});

function MyComponent() {
  return <PrimaryButton cs={styles}>Text</PrimaryButton>;
}
```

> Note:
> Most of our components support using the `cs` prop to apply the static styles. 
> It merges everything together and applies `className` and `style` attributes to a React element

#### Performance Benefits

`createStyles` is performant because:

- Styles are statically evaluated when styles are defined outside the render function
- No new StyleSheets are injected during render
- It works well with the browser's selector cache

### `createStencil`

`createStencil` a reusable function that returns `style` and `className` props in an object. A Stencil should apply to a single element. If your component has nested elements, you can youse `parts` to target those elements in the Stencil. If your component is a compound component, a stencil should be created for each subcomponent. If your component is a config component, a stencil can have nested styles.

We created Stencils as the reusable primitive of components. Stencils provide:

- `vars`: CSS variables for dynamic properties
- `base`: base styles to any component
- `modifier`: modifiers like “size = small,medium,large” or “color=red,blue,etc”
- `parts`: matching sub-elements that are part of a component
- `compound`: compound modifiers - styles that match multiple modifiers

#### Basic Example

In the example below, Stencils allow you to dynamically style elements or components based on properties.

```tsx
const themedCardStencil = createStencil({
  vars: {
    // Create CSS variables for the color of the header
    headerColor: '',
  },
  parts: {
    // Allows for styling a sub element of the component that may not be exposed through the API
    header: 'themed-card-header',
    body: 'themed-card-body',
  },
  base: ({headerPart, headerColor}) => ({
    padding: system.space.x4,
    boxShadow: system.depth[2],
    backgroundColor: system.color.bg.default,
    color: system.color.text.default,
    // Targets the header part via [data-part="themed-card-header"]"]
    [headerPart]: {
      color: headerColor,
    },
  }),
  modifiers: {
    isDarkTheme: {
      // If the prop `isDarkTheme` is true, style the component and it's parts
      true: ({headerPart, bodyPart}) => ({
        backgroundColor: system.color.bg.contrast.default,
        color: system.color.text.inverse,
        [`${headerPart}, ${bodyPart}`]: {
          color: system.color.text.inverse,
        },
      }),
    },
  },
});

export const CreateStencil = ({isDarkTheme, headerColor, elemProps}) => {
  const [darkTheme, setIsDarkTheme] = React.useState(false);
  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setIsDarkTheme(event.target.checked);
  };
  return (
    <div>
      <FormField>
        <FormField.Label>Toggle Dark Theme</FormField.Label>
        <FormField.Input as={Switch} onChange={handleChange} checked={darkTheme} />
      </FormField>

      <Card cs={themedCardStencil({isDarkTheme: darkTheme, headerColor})} {...elemProps}>
        <Card.Heading {...themedCardStencil.parts.header}>Canvas Supreme</Card.Heading>
        <Card.Body {...themedCardStencil.parts.body}>
          Our house special supreme pizza includes pepperoni, sausage, bell peppers, mushrooms,
          onions, and oregano.
        </Card.Body>
      </Card>
    </div>
  );
};
```

#### When to Use `createStencil`

- When you're styling parts of a component that rely on dynamic properties.
- When you want to create a reusable component with dynamic styles.

Use a Stencil when building reusable components that have dynamic styles and properties.

#### Concepts

**Base styles**

Base styles are always applied to a Stencil. All your default styles should go here. Base styles support psuedo selectors like `:focus-visible` or `:hover` as well as child selectors. Any selector supported by `@emotion/css` is valid here. All styles must be static and statically analyzable by the tranformer. If you need dynamic styling, look at Variables and Modifiers.

**Variables**

Variables allow some properties to be dynamic. They work by creating [CSS Variables](https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties) with unique names and are applied using the [style](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style) property of an element to locally scope an override. Since we don't have access to those names, we need a function wrapper around our style objects. This includes `base`, `modifiers`, and `compound` modifiers.

Here's a simplified example:

```tsx
const myStencil = createStencil({
  vars: {
    defaultColor: 'red' // default value
    nonDefaultedColor: '', // will allow for uninitialization
  },
  base: ({defaultColor}) => {
    color: defaultColor // `defaultColor` is '--defaultColor-abc123', not 'red'
  }
})

const elemProps = myStencil({color: 'blue'}) // {style: {'--defaultColor-abc123': 'blue'}}

<div {...elemProps} />
```

This will produce the following HTML:

```html
<style>
  .css-abc123 {
    --defaultColor-abc123: red;
    color: var(--defaultColor-abc123);
  }
</style>
<div class="css-123abc" style="--defaultColor-abc123: blue;"></div>
```

The element will have a `color` property of `'blue'` because the element style is the highest specificity and wins over a local class name. In the "Styles" tab of developer tools, it will look like the following:

```
element.style {
  --defaultColor-abc123: blue;
}

.css-abc123 {
  --defaultColor-abc123: red;
  color: var(--defaultColor-abc123); // blue
}
```

Variables are automatically added to the config of a Stencil. They share the same namespace as modifiers, so **do not have a modifier with the same name as a variable**.

> Note:
> Variables should be used sparingly. Style properties can be easily overridden without variables. 
> Variables are useful if you want to expose changing properties regardless of selectors.
> For example, Buttons use variables for colors of all states (hover, active, focus, disabled, and nested icons). 
> Without variables, overriding the focus color would require deeply nested selector overrides.

**Cascading Variables**

Notice the `nonDefaultedColor` is not included in the base styles like `defaultColor` was. If a variable has an empty string, it will can be uninitialized. Stencil variables with a default value will create a "cascade barrier". A cascade barrier prevents the variable from "leaking" into the component. For example, if a `Card` component was rendered within another `Card` component, the variables from the parent `Card` would not leak into the child `Card` component. But there are times where a component expects a parent component to set a CSS variable and that it should cascade to the component. An example of this is the relationship between `SystemIcon` and `Button`. The `Button` components set the `SystemIcon` variables and they should cascade into the `SystemIcon` component.

> Note:
> Non-cascade variables _could_ be initialized. If you use uninitialized variables, be sure to use a fallback in your styles.

```tsx
const myStencil = createStencil({
  vars: {
    color: '', // uninitialized
  },
  base({color}) {
    return {
      // provide a fallback. A uninitialized CSS variable will fall back to `initial`.
      // for the `color` CSS property, that's most likely black (default text color)
      color: cssVar(color, 'red'),
    };
  },
});
```

**Nested Variables**

Variables can be nested one level. This can be useful for colors with different psuedo selectors like `:hover` or `:focus`. Here's an example:

```tsx
const myStencil = createStencil({
  vars: {
    default: {
      color: 'red'
    },
    hover: {
      color: 'blue'
    },
    focus: {
      color: 'orange'
    }
  },
  base: ({default, hover, focus}) => {
    color: default.color,
    '&:hover': {
      color: hover.color
    },
    '&:focus': {
      color: focus.color
    }
  }
})
```

**Modifiers**

Modifiers are modifications to base styles. It should be used to change the appearance of a base style. For example, a button may have a modifier for "primary" or "secondary" which may change the visual emphasis of the button. Each modifier has its own CSS class name and the stencil will return the correct CSS classes to apply to an element based on what modifiers are active.

```tsx
const buttonStencil = createStencil({
  base: {
    padding: 5
    // base styles
  },
  modifiers: {
    variant: { // modifier name
      primary: {
        background: 'blue'
      },
      secondary: {
        background: 'gray'
      }
    }
  },
  defaultModifiers: {
    variant: 'secondary'
  }
})

const elemProps = myStencil({variant: 'primary'}) // {className: "css-a0 css-a1"}

<div {...elemProps} />
```

The HTML may look something like this:

```html
<style>
  .css-a0 {
    padding: 5px;
  }
  .css-a1 {
    background: 'blue';
  }
  .css-a2 {
    background: 'gray';
  }
</style>
<div class="css-a0 css-a1"></div>
```

The optional `defaultModifiers` config property will default modifiers to a value. If a modifier is not passed to the stencil, the default will be used.

```tsx
myStencil(); // className will be `'css-a0 css-a2'`
```

**Compound Modifiers**

A compound modifier creates a new CSS class for the intersection of two or more modifiers. Each modifier can have its own separate CSS class while the intersection is a different CSS class.

For example:

```tsx
const buttonStencil = createStencil({
  base: {
    padding: 10,
    // base styles
  },
  modifiers: {
    size: {
      // modifier name
      large: {
        padding: 20,
      },
      small: {
        padding: 5,
      },
    },
    iconPosition: {
      start: {
        paddingInlineStart: 5,
      },
      end: {
        paddingInlineEnd: 5,
      },
    },
  },
  compound: [
    {
      modifiers: {size: 'large', position: 'start'},
      styles: {
        paddingInlineStart: 15,
      },
    },
    {
      modifiers: {size: 'small', position: 'end'},
      styles: {
        paddingInlineEnd: 0,
      },
    },
  ],
});

<div {...buttonStencil()} />
<div {...buttonStencil({size: 'small'})} />
<div {...buttonStencil({size: 'small', iconPosition: 'end'})} />
```

The HTML will look something like this:

```html
<style>
  .a0 {
    padding: 10px;
  }
  .a1 {
    padding: 20px;
  }
  .a2 {
    padding: 5px;
  }
  .a3 {
    padding-inline-start: 5px;
  }
  .a4 {
    padding-inline-end: 5px;
  }
  .a5 {
    padding-inline-start: 15px;
  }
  .a6 {
    padding-inline-start: 0px;
  }
</style>
<div class="a0"></div>
<div class="a0 a2"></div>
<div class="a0 a2 a4 a6"></div>
```

Notice the stencil adds all the class names that match the base, modifiers, and compound modifiers.

**Variables and Modifiers with same keys**

It is possible to have a variable and modifier sharing the same key. The Stencil will accept either the modifier option or a string. The value will be sent as a variable regardless while the modifer will only match if it is a valid modifer key.

```tsx
const buttonStencil = createStencil({
  vars: {
    width: '10px',
  },
  base({width}) {
    return {
      width: width,
    };
  },
  modifiers: {
    width: {
      zero: {
        width: '0', // overrides base styles
      },
    },
  },
});

// `'zero'` is part of autocomplete
myStencil({width: 'zero'});
// returns {className: 'css-button css-button--width-zero', styles: { '--button-width': 'zero'}}

// width also accepts a string
myStencil({width: '10px'});
// returns {className: 'css-button', styles: { '--button-width': '10px'}}
```

#### Styling Elements via Component Parts

The goal of compound components is to expose one component per semantic element. Most of the time this means a 1:1 relationship of a component and DOM element. Sometimes a semantic element contains non-semantic elements for styling. An example might be a `<button>` with a icon for visual reinforcement, and a label for a semantic label. The semantic element is the `<button>` while the icon has no semantic value and the label automatically provides the semantic button with an accessible name. In order to style the icon and label elements, you have to know the DOM structure to target those specific elements in order to style it.

```jsx
import {createStencil} from '@workday/canvas-kit-styling';

const myButtonStencil = createStencil({
  base: {
    background: 'transparent',
    i: {
      // ...icon styles
    },
    span: {
      // ...label styles
    },
    ':hover': {
      // ...hover button styles
      i: {
        // ...hover icon styles
      },
      span: {
        // ...hover label styles
      },
    },
  },
});

const MyButton = ({children, ...elemProps}) => {
  return (
    <button {...handleCsProp(elemProps, myButtonStencil())}>
      <i />
      <span>{children}</span>
    </button>
  );
};
```

**Using Component Parts to Style Elements**

To style elements in the render function, we'll need to choose what elements to add the parts to. In the example below, we're able to spread the parts directly to elements. The Stencil will generate the type and value most appropriate for the context the part is used. In the Stencil, the part is represented by a string that looks like `[data-part="{partValue}"]` and in the render function, it is an object that looks like `{'data-part': partValue}`.

```jsx
import {createStencil, handleCsProp} from '@workday/canvas-kit-styling';

const myButtonStencil = createStencil({
  parts: {
    icon: 'my-button-icon',
    label: 'my-button-label',
  },
  base: ({iconPart, labelPart}) => ({
    background: 'transparent',
    [iconPart]: {
      // `[data-part="my-button-icon"]`
      // ...icon styles
    },
    [labelPart]: {
      // `[data-part="my-button-label"]`
      // ...label styles
    },
    '&:hover': {
      // ...hover styles for button element
      [iconPart]: {
        // ...hover styles for icon part
      },
    },
  }),
});

const MyButton = ({children, ...elemProps}) => {
  return (
    <button {...handleCsProp(elemProps, myButtonStencil())}>
      <i {...myButtonStencil.parts.icon} /> {/* data-part={my-button-icon} */}
      <span {...myButtonStencil.parts.label}>{children}</span> {/* data-part={my-button-label} */}
    </button>
  );
};
```

As a reusable component, you can use component parts to style elements that are not exposed in the API. Consumers can also use the type safe Stencil to target that element to style it as well. As a general rule, a Stencil maps to a component. Multiple Stencils per component usually means nested elements that are not targets for style overrides.

> Note
> While component parts are a way to give access to elements in order to style, they should be used sparingly. 
> Using component parts increases CSS specificity. 
> A component part should not be used on a nested component that has its own Stencil. The result will be any style properties defined with a component part will have a higher specificity than other styles.

## Converting from @emotion/styled

The most difficult part of understanding styling without Emotion's runtime is the mindset shift. You are using CSS to merge properties instead of JavaScript. This is essential to remove the runtime of Emotion. We'll use a contrived button example using `@emotion/styled` and our styling solution to step through the differences.

### Button using `@emotion/styled`

```tsx
import React from 'react';
import styled from '@emotion/styled';

interface ButtonProps {
  variant: 'primary' | 'secondary' | 'danger';
  size: 'large' | 'medium' | 'small';
  backgroundColor?: string;
  children?: React.ReactNode;
}

const StyledButton = styled('button')<ButtonProps>(
  {
    // base styles
    fontSize: '1rem',
    display: 'flex',
    borderRadius: '1rem',
  },
  // variant styles
  ({variant, backgroundColor}) => {
    switch (variant) {
      case 'primary':
        return {
          background: backgroundColor || 'blue',
          color: 'white',
        };
      case 'secondary':
        return {
          background: backgroundColor || 'gray',
        };
      case 'danger':
        return {
          background: backgroundColor || 'red',
        };
      default:
        return {};
    }
  },
  // size styles
  ({size}) => {
    switch (size) {
      case 'large':
        return {
          fontSize: '1.4rem',
          height: '2rem',
        };
      case 'medium':
        return {
          fontSize: '1rem',
          height: '1.5rem',
        };
      case 'small':
        return {
          fontSize: '0.8rem',
          height: '1.2rem',
        };
      default:
        return {};
    }
  }
);

export const EmotionButton = () => {
  return (
    <div style={{display: 'flex', flexDirection: 'column', gap: '1rem'}}>
      <div style={{display: 'flex', gap: '1rem'}}>
        <StyledButton variant="primary" size="large">
          Primary Large
        </StyledButton>
        <StyledButton variant="primary" size="medium">
          Primary Medium
        </StyledButton>
        <StyledButton variant="primary" size="small">
          Primary Small
        </StyledButton>
      </div>
      <div style={{display: 'flex', gap: '1rem'}}>
        <StyledButton variant="secondary" size="large">
          Secondary Large
        </StyledButton>
        <StyledButton variant="secondary" size="medium">
          Secondary Medium
        </StyledButton>
        <StyledButton variant="secondary" size="small">
          Secondary Small
        </StyledButton>
      </div>
      <div style={{display: 'flex', gap: '1rem'}}>
        <StyledButton variant="danger" size="large">
          Danger Large
        </StyledButton>
        <StyledButton variant="danger" size="medium">
          Danger Medium
        </StyledButton>
        <StyledButton variant="danger" size="small">
          Danger Small
        </StyledButton>
      </div>
      <div style={{display: 'flex', gap: '1rem'}}>
        <StyledButton variant="danger" size="large" backgroundColor="orange">
          Custom Large
        </StyledButton>
        <StyledButton variant="danger" size="medium" backgroundColor="orange">
          Custom Medium
        </StyledButton>
        <StyledButton variant="danger" size="small" backgroundColor="orange">
          Custom Small
        </StyledButton>
      </div>
    </div>
  );
};
```

If we inspect each button, we'll notice each has a different class name. They all look like `css-{hash}`:

For example, the Primary buttons:

- Primary Large: `css-oqv33j`
- Primary Medium: `css-1nhzlx`
- Primary Small: `css-1ygk6q`

This means each button is a unique style sheet insert by Emotion. If we render each permutation at once, there will only be one expensive [style recalculation](https://microsoftedge.github.io/DevTools/explainers/StyleTracing/explainer.html)

Converting to use the Canvas Kit Styling solution means organizing a little different. In our example, it is already organized well, but conditionals might be anywhere in the style functions and will need to be organized in groups.

### Button using only `createStyles`

What are we really trying to accomplish? [BEM](https://getbem.com/introduction) fits well with compound components. BEM stands for Block, Element, Modifer. In compound components, "Block" refers to a container component while "Element" refers to subcomponets. The "Modifer" refers to changing the appearance of a block.

In our example, all styles that are common to all appearances of our button. It might be `borderRadius`, `fontFamily`. We can use `createStyles` to define these styles:

```ts
const baseStyles = createStyles({
  fontSize: '1rem',
  display: 'flex',
  borderRadius: '1rem',
});
```

The `variant` modifiers use a variable prop called `backgroundColor` which cannot be variable at runtime. We need to use a CSS Variable for this.

We can create modifers using `createStyles` and organize them in an object:

```ts
const modifierStyles = {
  variant: {
    primary: createStyles({
      background: `var(--background-color-button, blue)`,
      color: 'white',
    }),
    secondary: createStyles({
      background: `var(--background-color-button, gray)`,
    }),
    danger: createStyles({
      background: `var(--background-color-button, red)`,
    }),
  },
  size: {
    large: createStyles({
      fontSize: '1.4rem',
      height: '2rem',
    }),
    medium: createStyles({
      fontSize: '1rem',
      height: '1.5rem',
    }),
    small: createStyles({
      fontSize: '0.8rem',
      height: '1.2rem',
    }),
  },
};
```

Each modifier value uses `createStyles` which returns a different class name. This means we can create a "Primary Large" button by applying these modifiers to the `className` prop of a React element:

```jsx
<button className={`${baseStyles} ${modifierStyles.variant.primary} ${modifierStyles.size.large}`}>
  Primary Large
</button>
```

This will create a button with 3 separate class names applied. `@emotion/styled` only applies a single css class name.

```html
<!-- @emotion/styled -->
<button class="css-108wq52">Primary Large</button>

<!-- createStyles -->
<button class="css-puxv12 css-puxv13 css-puxv16">Primary Large</button>
```

If you want to change the background color, you'll have to pass it using `style`:

```jsx
<button
  className={`${baseStyles} ${modifierStyles.size.large}`}
  style={{'--color-background-button': 'orange'}}
>
  Orange Large
</button>
```

The output HTML will look like:

```html
<button class="css-puxv12 css-puxv16" style="--color-background-button: orange;">
  Orange Large
</button>
```

This works because CSS Custom Properties cascade values. The `style` attribute defines styles on the element directly. This is a runtime in React that allows us to change a style without a new style block - the styles can be static, but we can still have variable property values.

```tsx
import React from 'react';
import {createStyles} from '@workday/canvas-kit-styling';

interface ButtonProps {
  variant: 'primary' | 'secondary' | 'danger';
  size: 'large' | 'medium' | 'small';
  backgroundColor?: string;
  children?: React.ReactNode;
}

const baseStyles = createStyles({
  fontSize: '1rem',
  display: 'flex',
  borderRadius: '1rem',
});

const modifierStyles = {
  variant: {
    primary: createStyles({
      background: `var(--button-background-color, blue)`,
      color: 'white',
    }),
    secondary: createStyles({
      background: `var(--button-background-color, gray)`,
    }),
    danger: createStyles({
      background: `var(--button-background-color, red)`,
    }),
  },
  size: {
    large: createStyles({
      fontSize: '1.4rem',
      height: '2rem',
    }),
    medium: createStyles({
      fontSize: '1rem',
      height: '1.5rem',
    }),
    small: createStyles({
      fontSize: '0.8rem',
      height: '1.2rem',
    }),
  },
};

const Button = ({variant, size, backgroundColor, children}: ButtonProps) => {
  const className = [baseStyles, modifierStyles.variant[variant], modifierStyles.size[size]].join(
    ' '
  );
  const style = {'--button-background-color': backgroundColor} as React.CSSProperties;
  return (
    <button className={className} style={style}>
      {children}
    </button>
  );
};

export const ManualStylesButton = () => {
  return (
    <div style={{display: 'flex', flexDirection: 'column', gap: '1rem'}}>
      <div style={{display: 'flex', gap: '1rem'}}>
        <Button variant="primary" size="large">
          Primary Large
        </Button>
        <Button variant="primary" size="medium">
          Primary Medium
        </Button>
        <Button variant="primary" size="small">
          Primary Small
        </Button>
      </div>
      <div style={{display: 'flex', gap: '1rem'}}>
        <Button variant="secondary" size="large">
          Secondary Large
        </Button>
        <Button variant="secondary" size="medium">
          Secondary Medium
        </Button>
        <Button variant="secondary" size="small">
          Secondary Small
        </Button>
      </div>
      <div style={{display: 'flex', gap: '1rem'}}>
        <Button variant="danger" size="large">
          Danger Large
        </Button>
        <Button variant="danger" size="medium">
          Danger Medium
        </Button>
        <Button variant="danger" size="small">
          Danger Small
        </Button>
      </div>
      <div style={{display: 'flex', gap: '1rem'}}>
        <Button variant="danger" size="large" backgroundColor="orange">
          Custom Large
        </Button>
        <Button variant="danger" size="medium" backgroundColor="orange">
          Custom Medium
        </Button>
        <Button variant="danger" size="small" backgroundColor="orange">
          Custom Small
        </Button>
      </div>
    </div>
  );
};
```

### Button using all utilities

If we want variables that are hashed and make it easier to define and use, we have `createVars`. There are also edge cases for modifiers like allowing `undefined`, so we made a `createModifiers` function as well. Both `createModifiers` and `createVars` return a function that makes it easier to call with inputs and will return the correct output.

For example, `createModifiers`:

```tsx
const myModifiers = createModifiers({
  size: {
    large: 'button-large',
    small: 'button-small'
  }
})

myModifiers.size.large // 'button-large'

// the function knows what config can be passed
// and what restrictions each value has
myModifiers({size: 'large'}) // 'button-large'
myModifiers({size: 'small'}) // 'button-small'
myModifiers() // ''

// in a component
<div className={myModifiers({size: 'large'})} /> // <div class="button-large" />
```

`createVars`:

```tsx
const myVars = createVars('background', 'color')

myVars.color // something like `--color-{hash}`

// the function knows what keys are allowed
myVars({color: 'red'}) // {'--color-{hash}': 'red'}

// in a component
<div style={myVars({color: 'red'})} /> // <div style="--color-{hash}: red;">
```

## How To Customize Styles

There are multiple ways to customize styles for components within Canvas Kit. The approach you choose will depend on use case.

### Create Styles

#### Using `createStyles` with `cs` prop

Use `createStyles` in tandem with `cs` prop when you're overriding static styles and making small modifications to an existing Canvas Kit component like padding, color and flex properties. Take our `Text` component as an example.

```tsx
import {createStyles} from '@Workday/canvas-kit-styling';
import {system} from '@Workday/canvas-tokens-web';
import {Text} from '@Workday/canvas-kit-react/text';

const uppercaseTextStyles = createStyles({
  textTransform: 'uppercase',
  margin: system.space.x4
})
//...
<Text cs={uppercaseTextStyles}>My uppercased text</Text>;
```

> **Note:** `createStyles` handles wrapping our token variables in `var(--${token})`

You can also apply styles created via `createStyles` via `className`.

```tsx
import {createStyles} from '@Workday/canvas-kit-styling';
import {system} from '@Workday/canvas-tokens-web';
import {Text} from '@Workday/canvas-kit-react/text';

const uppercaseTextStyles = createStyles({
  textTransform: 'uppercase',
  margin: system.space.x4
})
//...
<Text className={uppercaseTextStyles}>My uppercased text</Text>;
```

If you need to dynamically apply styles based on some state or prop, use [Stencils](#stencils) instead.

## Stencils

Stencils can be useful when applying dynamic styles or building your own reusable component.

### Extending Stencils

[Stencils](https://workday.github.io/canvas-kit/?path=/docs/styling-getting-started-create-stencil--docs) help you organize the styling of reusable components into base styles, modifiers, and variables. The organization makes it more natural to produce static and clean CSS with optional extraction into CSS files.

Stencils that define variables, modifiers and base styles can be extended to create your own reusable component using Canvas Kit styles.

If we take `SystemIcon` component as an example, it defines `systemIconStencil` which defines styles for an icon. This stencil can be extended to build a custom icon component for your use case.

**Before v11** you'd have to use `systemIconStyles` function to overwrite styles for an icon:

```tsx
// Before v11
import {systemIconStyles} from '@workday/canvas-kit-react';
import {space} from '@workday/canvas-kit-react/tokens'; // old tokens

// old way of styling with Emotion styled
const StyledNavIcon = styled('span')(({size, iconStyles}){
  display: 'inline-flex',
  pointerEvents: 'unset',
  margin: `${space.xxxs} ${space.xxxs} 0 0`,
  padding: '0',
  'svg': {
    ...iconStyles,
    width: size,
    height: size,
  }
});

const NavIcon = ({iconColor, iconHover, iconBackground, iconBackgroundHover, icon, size}) => {
  // old way of styling with systemIconStyles function
  // systemIconStyles is deprecated in v11
  const iconStyles = systemIconStyles({
    fill: iconColor,
    fillHover: iconHover,
    background: iconBackground,
    backgroundHover: iconBackgroundHover,
  });

  // insert icon function used by platform or any other functionality here

  return (
    <StyledNavIcon
      icon={icon}
      size={size}
      iconStyles={iconStyles}
    />
  );
};
```

**From v11** you'd extend `systemIconStencil` to reuse its styles:

```tsx
// v11
import {createStencil} from '@workday/canvas-kit-styling';
import {system} from '@workday/canvas-tokens-web';
import {systemIconStencil} from '@workday/canvas-kit-react/icon';

const navIconStencil = createStencil({
  // We extend `systemIconStencil` to inherit it's base styles, modifiers and variables so that we can customize it
  extends: systemIconStencil,
  vars: {
    // These variables support our styling iconHover and iconBackgroundHover
    // they can be removed later and overwritten by `cs`.
    // Also note the variables have no value. This allows for cascading styles.
    fillHover: '',
    backgroundHover: '',
  },
  base: ({fillHover, backgroundHover}) => ({
    display: 'inline-flex',
    pointerEvents: 'unset',
    // instead of using our old tokens it's better to use our new system tokens
    margin: `${system.space.x1} ${system.space.x1} 0 0`,
    padding: '0',
    '&:hover, &.hover': {
      // systemIconStencil doesn't have hover specific variables
      // so we reassigned color and backgroundColor variables using pseudo-selector
      [systemIconStencil.vars.color]: fillHover,
      [systemIconStencil.vars.backgroundColor]: backgroundHover,
    },
  }),
});

// Your reusable NavIcon component using Stencils
const NavIcon = ({
  iconColor,
  iconHover,
  iconBackground,
  iconBackgroundHover,
  icon,
  size,
  ...elemProps
}) => {
  // insert icon function used by platform or any other functionality here

  return (
    <span
      icon={icon}
      {...handleCsProp(
        elemProps,
        navIconStencil({
          // Because we're extending systemIconStencil, it already has a size prop and applies size to the svg's width and height
          // so we don't need to set these variables in our navIconStencil
          size,
          // systemIconStencil already has color (for icon fill) and backgroundColor variables
          // so we assigned them to our prop values
          color: iconColor,
          backgroundColor: iconBackground,
          fillHover: iconHover,
          backgroundHover: iconBackgroundHover,
        })
      )}
    />
  );
};
```

Another example of Stencil extension and customization is our [CustomButton](https://workday.github.io/canvas-kit/?path=/story/components-buttons--docs#custom-styles) example. This example highlights the power of inheritance that you get from extending stencils.

## Merging Styles

### handleCsProp

But what about when using components that use `@emotion/react` or `@emotion/styled`? Those libraries use a different approach. Instead of multiple class names, they use a single, merged class name.

`handleCsProp` was created to handle integration with existing components that use the `css` prop from `@emotion/react` or the `styled` components from `@emotion/styled`. If a class name from one of those libraries is detected, style merging will follow the same rules as those libraries. Instead of multiple class names, a single class name with all matching properties is created. The `handleCsProp` also takes care of merging `style` props, `className` props, and can handle the `cs` prop:

```tsx
const myStencil = createStencil({
  // ...
});

const MyComponent = elemProps => {
  return <div {...handleProps(elemProps, myStencil({}))} />;
};

// All props will be merged for you
<MyComponent style={{color: 'red'}} className="my-classname" cs={{position: 'relative'}} />;
```

`handleCsProp` will make sure the `style` prop is passed to the `div` and that the `my-classname` CSS class name appears on the `div`'s class list. Also the `cs` prop will add the appropriate styles to the element via a CSS class name. If your component needs to handle being passed a `className`, `style`, or `cs` prop, use `handleCsProp`.

### mergeStyles (deprecated)

In v9, we used `@emotion/styled` or `@emotion/react` for all styling which is a runtime styling solution. Starting in v10, we're migrating our styling to a more static solution using `createStyles` and the `cs` prop.

For a transition period, we're opting for backwards compatibility. If style props are present, [styled components](https://emotion.sh/docs/styled) are used, or the [css prop](https://emotion.sh/docs/css-prop) is used in a component, Emotion's style merging will be invoked to make sure the following style precedence:

```
createStyles > CSS Prop > Styled Component > Style props
```

This will mean that any `css` prop or use of `styled` within the component tree _per element_ will cause style class merging. For example:

```tsx
import styled from '@emotion/styled';
import {createStyles} from '@workday/canvas-kit-styling';
import {mergeStyles} from '@workday/canvas-kit-react/layout';

const styles1 = createStyles({
  padding: 4,
});

const styles2 = createStyles({
  padding: 12,
});

const Component1 = props => {
  return <div {...mergeStyles(props, [styles1])} />;
};

const Component2 = props => {
  return <Component1 cs={styles2} />;
};

const Component3 = styled(Component1)({
  padding: 8,
});

const Component4 = props => {
  return <Component3 cs={styles2} />;
};

export default () => (
  <>
    <Component1 />
    <Component2 />
    <Component3 />
    <Component4 />
  </>
);
```

The `styled` component API is forcing `mergeStyles` to go into Emotion merge mode, which removes the `style1` class name and creates a new class based on all the merged style properties. So `.component3` is a new class created by Emotion at render time that merges `.style1` and `{padding: 8px}`. `Component4` renders `Component3` with a `cs` prop, but `Component3` is already in merge mode and so `Component4` will also merge all styles into a new class name of `.component4` that has the styles from `.style1`, `.component3`, and `{padding: 12px}`:

```html
<head>
  <style>
    .styles1 {
      padding: 4px;
    }
    .styles2 {
      padding: 8px;
    }
    .component3 {
      padding: 4px;
      padding: 8px;
    }
    .component4 {
      padding: 4px;
      padding: 8px;
      padding: 12px;
    }
  </style>
</head>

<div class="styles1"></div>
<div class="styles1 styles2"></div>
<div class="component3"></div>
<div class="component4"></div>
```

The `css` prop and `styled` component APIs will rewrite the `className` React prop by iterating over all class names and seeing if any exist within the cache. If a class name does exist in the cache, the CSS properties are copied to a new style property map until all the class names are evaluated and removed from the `className` prop. Emotion will then combine all the CSS properties and inject a new `StyleSheet` with a new class name and add that class name to the element.

The following example shows this style merging.

```tsx
import * as React from 'react';
import styled from '@emotion/styled';
import {jsx} from '@emotion/react';

import {Flex} from '@workday/canvas-kit-react/layout';
import {PrimaryButton} from '@workday/canvas-kit-react/button';
import {base} from '@workday/canvas-tokens-web';
import {createStyles, cssVar} from '@workday/canvas-kit-styling';

const backgroundColors = {
  cssProp: cssVar(base.orange500),
  styledComponent: cssVar(base.green500),
  styleProps: cssVar(base.magenta500),
  createStyles: cssVar(base.purple500),
};

const StyledPrimaryButton = styled(PrimaryButton)({
  backgroundColor: backgroundColors.styledComponent,
});

const styles = createStyles({
  backgroundColor: backgroundColors.createStyles,
});

const CSSProp = () => (
  <div
    style={{
      color: 'white',
      padding: '0 4px',
      height: 40,
      width: 100,
      backgroundColor: backgroundColors.cssProp,
    }}
  >
    CSS Prop
  </div>
);
const StyledComponent = () => (
  <div
    style={{
      color: 'white',
      padding: '0 4px',
      height: 40,
      width: 100,
      backgroundColor: backgroundColors.styledComponent,
    }}
  >
    Styled Component
  </div>
);
const CreateStyles = () => (
  <div
    style={{
      color: 'white',
      padding: '0 4px',
      height: 40,
      width: 100,
      backgroundColor: backgroundColors.createStyles,
    }}
  >
    createStyles
  </div>
);
const StyleProps = () => (
  <div
    style={{
      color: 'white',
      padding: '0 4px',
      height: 40,
      width: 100,
      backgroundColor: backgroundColors.styleProps,
    }}
  >
    Style Props
  </div>
);

// We use this object and cast to `{}` to keep TypeScript happy. Emotion extends the JSX interface
// to include the `css` prop, but the `jsx` function type doesn't accept the `css` prop. Casting to
// an empty object keeps TypeScript happy and the `css` prop is valid at runtime.
const cssProp = {css: {backgroundColor: backgroundColors.cssProp}} as {};

export const StylingOverrides = () => {
  return (
    <Flex flexDirection="column" minHeight="100vh" gap="s">
      <Flex flexDirection="column" gap="s">
        <h2>Buttons</h2>
        <Flex flexDirection="row" gap="s">
          <PrimaryButton cs={styles}>createStyles</PrimaryButton>
          {jsx(PrimaryButton, {...cssProp}, 'CSS Prop')}
          <StyledPrimaryButton>Styled Component</StyledPrimaryButton>
          <PrimaryButton backgroundColor={backgroundColors.styleProps}>Style Props</PrimaryButton>
        </Flex>
        <div>
          {jsx(
            PrimaryButton,
            {
              ...cssProp,
              cs: styles,
            },
            'createStyles + CSS Prop'
          )}
        </div>
        <div>
          <StyledPrimaryButton cs={styles}>createStyles + Styled Component</StyledPrimaryButton>
        </div>
        <div>
          <PrimaryButton cs={styles} backgroundColor={backgroundColors.styleProps}>
            createStyles + Style Props
          </PrimaryButton>
        </div>
        <div>
          <StyledPrimaryButton backgroundColor={backgroundColors.styleProps} cs={styles}>
            createStyles + Styled Component + Style Props
          </StyledPrimaryButton>
        </div>
        <div>
          {jsx(
            StyledPrimaryButton,
            {
              ...cssProp,
              backgroundColor: backgroundColors.styleProps,
              cs: styles,
            },
            'createStyles + CSS Prop + Styled Component + Style Props'
          )}
        </div>
        <div>{jsx(StyledPrimaryButton, {...cssProp}, 'CSS Prop + Styled Component')}</div>
        <div>
          {jsx(
            PrimaryButton,
            {
              ...cssProp,
              backgroundColor: backgroundColors.styleProps,
            },
            'CSS Prop + Style Props'
          )}
        </div>
        <div>
          <StyledPrimaryButton backgroundColor={backgroundColors.styleProps}>
            Styled Component + Style Props
          </StyledPrimaryButton>
        </div>
      </Flex>
      <div>
        <p>Legend:</p>
        <CreateStyles />
        <CSSProp />
        <StyledComponent />
        <StyleProps />
      </div>
      <p>
        Style Precedence: <strong>createStyles</strong> &gt; <strong>CSS Props</strong> &gt;{' '}
        <strong>Styled Component</strong> &gt; <strong>Style Props</strong>
      </p>
    </Flex>
  );
};
```

CSS style property merging works by [CSS specificity](https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity). If two matching selectors have the same specificity, the last defined property wins. Stencils take advantage of this by making all styles have the same specificity of `0-1-0` and inserting `base` styles, then `modifiers` (in order), then `compound` modifiers (in order). This means if a property was defined in `base`, a `modifier`, and a `compound` modifier, the `compound` modifier would win because it is the last defined. This should be the expected order.

> Caution
> While we support `mergeStyles` we'd advise against using this in your components so that users can get the performance benefit of static styling using utilities like `createStyles` and `createStencil` in tandem with the `cs` prop.

## Canvas Kit Styling Utilities

A collection of helpful functions for styling with `@workday/canvas-kit-styling`. While they're fairly simple, they make styling much nicer.

### Pixels to Rem

This function converts a `px` value (number) to `rem` (string). This keeps you from having to do any tricky mental division or write irrational numbers.

```ts
import {px2rem} from '@workday/canvas-kit-styling';
import {system} from '@workday/canvas-tokens-web';

const styles = {
  // returns '0.0625rem'
  margin: px2rem(1),
};
```

### Calc Functions

Calc functions are useful for doing basic math operations with CSS `calc()` and variables. They will also wrap variables automatically in `var()`.

#### Add

This function returns a CSS `calc()` addition string.

```ts
import {calc} from '@workday/canvas-kit-styling';
import {system} from '@workday/canvas-tokens-web';

const styles = {
  // returns 'calc(var(--cnvs-sys-space-x1) + 0.125rem)'
  padding: calc.add(system.space.x1, '0.125rem'),
};
```

#### Subtract

This function returns a CSS `calc()` subtraction string.

```ts
import {calc} from '@workday/canvas-kit-styling';
import {system} from '@workday/canvas-tokens-web';

const styles = {
  // returns 'calc(var(--cnvs-sys-space-x1) - 0.125rem)'
  padding: calc.subtract(system.space.x1, '0.125rem'),
};
```

#### Multiply

This function returns a CSS `calc()` multiplication string.

```ts
import {calc} from '@workday/canvas-kit-styling';
import {system} from '@workday/canvas-tokens-web';

const styles = {
  // returns 'calc(var(--cnvs-sys-space-x1) * 3)'
  padding: calc.multiply(system.space.x1, 3),
};
```

#### Divide

This function returns a CSS `calc()` division string

```ts
import {calc} from '@workday/canvas-kit-styling';
import {system} from '@workday/canvas-tokens-web';

const styles = {
  // returns 'calc(var(--cnvs-sys-space-x1) / 2)'
  padding: calc.divide(system.space.x1, 2),
};
```

#### Negate

This function negates a CSS variable to give you the opposite value. This keeps you from having to wrap the variable in `calc()` and multiplying by `-1`.

```ts
import {calc} from '@workday/canvas-kit-styling';
import {system} from '@workday/canvas-tokens-web';

const styles = {
  // returns 'calc(var(--cnvs-sys-space-x4) * -1)'
  margin: calc.negate(system.space.x4),
};
```

### keyframes

The `keyframes` function re-exports the [Emotion CSS keyframes](https://emotion.sh/docs/keyframes) function, but is compatible with a custom Emotion instance and is understood by the Static style transformer.

#### Example

```tsx
import {system} from '@workday/canvas-tokens-web';
import {createComponent} from '@workday/canvas-kit-react/common';
import {
  handleCsProp,
  keyframes,
  createStencil,
  calc,
  px2rem,
  CSProps,
} from '@workday/canvas-kit-styling';

/**
 * Keyframe for the dots loading animation.
 */
const keyframesLoading = keyframes({
  '0%, 80%, 100%': {
    transform: 'scale(0)',
  },
  '40%': {
    transform: 'scale(1)',
  },
});

export const loadingStencil = createStencil({
  base: {
    display: 'inline-flex',
    gap: system.space.x2,
    width: system.space.x4,
    height: system.space.x4,
    fontSize: system.space.zero,
    borderRadius: system.shape.round,
    backgroundColor: system.color.bg.muted.softer,
    outline: `${px2rem(2)} solid transparent`,
    transform: 'scale(0)',
    animationName: keyframesLoading,
    animationDuration: calc.multiply('150ms', 35),
    animationIterationCount: 'infinite',
    animationTimingFunction: 'ease-in-out',
    animationFillMode: 'both',
  },
});

/**
 * A simple component that displays three horizontal dots, to be used when some data is loading.
 */
export const LoadingDot = createComponent('div')({
  displayName: 'LoadingDots',
  Component: ({...elemProps}: CSProps, ref, Element) => {
    return <Element ref={ref} {...handleCsProp(elemProps, loadingStencil())}></Element>;
  },
});
```

### injectGlobal

The `injectGlobal` function re-exports the [Emotion CSS injectGlobal](https://emotion.sh/docs/@emotion/css#global-styles) function, but is compatible with a custom Emotion instance and is understood by the Static style transformer. It will also wrap our CSS tokens to ensure you can inject global styles using our CSS variables.

```tsx
injectGlobal({
  ...fonts,
  'html, body': {
    fontFamily: system.fontFamily.default,
    margin: 0,
    minHeight: '100vh',
    ...system.type.heading.lg,
  },
  '#root, #root < div': {
    minHeight: '100vh',
  },
});
```

#### Example

```tsx
import {createRoot} from 'react-dom/client';
import {fonts} from '@workday/canvas-kit-react-fonts';
import {system} from '@workday/canvas-tokens-web';
import {cssVar, injectGlobal} from '@workday/canvas-kit-styling';
import {App} from './App';

import '@workday/canvas-tokens-web/css/base/_variables.css';
import '@workday/canvas-tokens-web/css/brand/_variables.css';
import '@workday/canvas-tokens-web/css/component/_variables.css';
import '@workday/canvas-tokens-web/css/system/_variables.css';

//@ts-ignore
injectGlobal({
  ...fonts,
  'html, body': {
    fontFamily: cssVar(system.fontFamily.default),
    margin: 0,
    minHeight: '100vh',
  },
  '#root, #root < div': {
    minHeight: '100vh',
    ...system.type.body.sm,
  },
});

const container = document.getElementById('root')!;
const root = createRoot(container);
root.render(<App />);
```

### Custom Emotion Instance

Static style injection happens during the parsing stages of the files. This means when you `import` a component that uses static styling, the styles are injected immediately. This happens way before rendering, so using the Emotion [CacheProvider](https://emotion.sh/docs/cache-provider) does not work. A custom instance must be created _before_ any style utilities are called - during the bootstrapping phase of an application. We don't have a working example because it requires an isolated application, but here's an example adding a `nonce` to an application:

```tsx
// bootstrap-styles.ts
import {createInstance} from '@workday/canvas-kit-styling';

// assuming this file is being called via a `script` tag and that
// script tag has a `nonce` attribute set from the server
createInstance({nonce: document.currentScript.nonce});

// index.ts
import React from 'react';
import ReactDOM from 'react-dom';

// call the bootstrap in the import list. This has the side-effect
// of creating an instance
import './bootstrap-styles';

import App from './App';

const root = ReactDOM.createRoot(document.querySelector('#root'));

root.render(<App />);

// App.tsx
import React from 'react';

// The following will create and inject styles. We cannot adjust
// the Emotion instance after this import
import {PrimaryButton} from '@workday/canvas-kit-react/button';

// if we call `createInstance` here, we'll get a warning in
// development mode

export default () => {
  return <PrimaryButton>Button</PrimaryButton>;
};
```