Install @ant-design/cssinjs
masterInstall the @ant-design/cssinjs package using your preferred package manager.
npm install @ant-design/cssinjs
# or
yarn add @ant-design/cssinjs
# or
pnpm add @ant-design/cssinjsrepository·master·Indexed 43 days ago
https://github.com/ant-design/cssinjsA component-level CSS-in-JS solution used in Ant Design, acting as a subset of Emotion with a specialized design token logic wrapper. Version 2.1.2 provides tools for style injection via StyleProvider, theme creation with createTheme, and SSR style extraction using extractStyle. It includes transformers for px2rem and logical properties, as well as hooks like useCacheToken and useStyleRegister for managing design tokens and CSS variables.
Install the @ant-design/cssinjs package using your preferred package manager.
npm install @ant-design/cssinjs
# or
yarn add @ant-design/cssinjs
# or
pnpm add @ant-design/cssinjsYou can transform CSSObjects before they are injected into the document by passing an array of transformers to the transformers prop of StyleProvider.
legacyLogicalPropertiesTransformerConverts logical properties to legacy properties for better compatibility (e.g., converting marginBlockStart to marginTop). It supports:
insetmarginpaddingborderpx2remTransformerConverts pixel (px) units to rem units.
import {
legacyLogicalPropertiesTransformer,
StyleProvider,
} from '@ant-design/cssinjs';
export default () => (
<StyleProvider transformers={[legacyLogicalPropertiesTransformer]}>
<MyApp />
</StyleProvider>
);You can wrap your styles in CSS @layer using the layer option in useStyleRegister. This allows you to manage CSS specificity and ensure certain styles (like base or reset styles) are applied in a predictable order relative to component styles.
export interface LayerConfig {
name: string;
dependencies?: string[];
}When dependencies are provided, the library will inject @layer name, dependency1, dependency2; to establish the layer hierarchy.
const layerConfig = {
name: 'components',
dependencies: ['reset', 'base'],
};The @ant-design/cssinjs library supports using CSS variables within its styling system. This allows for dynamic theme updates and easier integration with external CSS variable-based design systems. You can define styles that reference CSS variables (e.g., var(--my-color)) directly within the cssinjs functions.
// Note: The actual implementation is located in ../examples/css-var.tsx
// This demo demonstrates how to leverage CSS variables within the cssinjs workflow.The animation demo demonstrates how to implement and manage animations within the @ant-design/cssinjs ecosystem. You can view the implementation details and usage patterns in the source example file.
// See implementation in ../examples/animation.tsxThe logicalProperties transformer allows you to convert physical CSS properties (like margin-left or padding-top) into logical properties (like margin-inline-start or padding-block-start). This is useful for supporting multi-directional layouts and internationalization (i18n) where text direction might change.
// Example usage of logicalProperties transformer
// Refer to ../examples/logicalProperties.tsx for implementation detailsThe px2rem transformer automatically converts pixel (px) values into rem units. This is commonly used to implement responsive typography and spacing based on the root font size.
// Example usage of px2rem transformer
// Refer to ../examples/px2rem.tsx for implementation detailsThe StyleProvider component allows you to configure how styles are injected, cached, and transformed. It is the primary way to manage the CSS-in-JS context in your application.
| Prop | Type | Default | Description |
|---|---|---|---|
autoClear | boolean | false | Clear inject style element when component remove. |
cache | CacheEntity | - | Config cssinjs cache entity. Only set when you need ssr to extract style on you own. |
hashPriority | 'low' | 'high' | 'low' | Use :where selector to reduce hashId css selector priority. |
container | Element | ShadowRoot | document.head | Tell cssinjs where to inject style in. |
ssrInline | boolean | false | Component will render inline <style /> for fallback in SSR. (Not recommended). |
transformers | Transformer[] | - | Transform css before inject in document. Note: transformers do not support dynamic update. |
The extractStyle function extracts styles from a provided cache instance and returns them as a string. This is primarily used for SSR to collect styles generated during rendering.
cache (Cache): The cache instance containing the styles.options (object | boolean, optional): Options for extracting the styles.plain (boolean, optional): If true, the styles will be returned in plain format. Default is false.types (string | string[], optional): The types of styles to extract. Default is ['style', 'token', 'cssVar'].string: The extracted styles as a string.import { extractStyle, createCache } from '@ant-design/cssinjs';
// Create and populate cache
const cache = createCache();
// Note: In actual usage, the cache is typically populated automatically when rendering components
// Extract styles
const styles = extractStyle(cache, { plain: true, types: ['style', 'token'] });
// Use the extracted styles
const styleElement = document.createElement('style');
styleElement.innerHTML = styles;
document.head.appendChild(styleElement);When using useCacheToken, the cssVar option controls how design tokens are converted into CSS variables. This is essential for implementing dynamic theming via CSS variables.
| Option | Type | Description |
|---|---|---|
key | string | Required. A unique identifier for the current theme. Used to track and clean up styles. |
prefix | string | A prefix applied to the generated CSS variable names. |
hashed | boolean | If true, the generated class name will include a hash. |
unitless | Record<string, boolean> | Specifies tokens that should not have units (like px or rem) appended. |
ignore | Record<string, boolean> | Specifies tokens that should be skipped during CSS variable transformation. |
preserve | Record<string, boolean> | Specifies tokens that should retain their original value instead of being transformed. |
cssVar: {
key: 'my-unique-theme-key',
prefix: '--ant-',
unitless: { borderRadius: true },
ignore: { color: true },
preserve: { fontSize: true },
hashed: true,
}The useCSSVarRegister hook is used to transform design tokens into CSS variables and register them in the global cache. It handles the transformation of tokens (applying prefixes, unitless settings, or ignoring specific keys), generates a unique style ID, and injects the resulting CSS variable declarations into the DOM.
When calling useCSSVarRegister, you provide a config object and a function fn that returns the original tokens.
| Option | Type | Description |
|---|---|---|
path | string[] | A path array used to identify the style hierarchy. |
key | string | The unique key for this token set. |
prefix | string (optional) | A prefix applied to the generated CSS variable names. |
unitless | Record<string, boolean> (optional) | A map specifying which token keys should have their units removed. |
ignore | Record<string, boolean> (optional) | A map specifying which token keys should be ignored during transformation. |
scope | string | string[] (optional) | Defines the scope for the CSS variables. |
token | any | The token object, which must contain a _tokenKey property. |
hashId | string (optional) | An optional hash ID for class name generation. |
nonce | string | (() => string) (optional) | A CSP nonce for secure style injection. |
The hook returns a CSSVarCacheValue tuple containing:
cssVarToken: The transformed token object containing CSS variable references.cssVarStr: The raw CSS variable string.styleId: The unique identifier for the injected style.cssVarKey: The key used for registration.const [cssVarToken, cssVarStr, styleId, cssVarKey] = useCSSVarRegister({
path: ['some', 'path'],
key: 'myTokenKey',
prefix: 'myPrefix',
token: { _tokenKey: 'tokenKey' },
// ... other options
}, () => originalTokens);Transformers allow you to manipulate CSS objects during the styling process. The package exports several built-in transformers:
autoPrefixTransformer: Adds vendor prefixes to CSS properties.legacyLogicalPropertiesTransformer: Converts logical properties to physical properties for older browser support.px2remTransformer: Converts pixel values to rem units.