CSS Custom Properties, also known as CSS variables, let you define reusable style values that can be shared across your app, like colors, spacing, and typography and even updated dynamically.
CSS variables start with --
and are accessed using var(--name)
.
:root {
--primary-color: #10b981;
--font-size: 16px;
}
Then use them anywhere:
button {
background-color: var(--primary-color);
font-size: var(--font-size);
}
Where to Save CSS Variables
You can define them globally in a dedicated file such as variables.css
:
/* src/styles/variables.css */
:root {
--primary-color: #10b981;
--secondary-color: #3b82f6;
--border-radius: 8px;
--padding: 12px;
--font-size: 16px;
}
Import once in your entry file (e.g., main.tsx
or App.tsx
):
import './styles/variables.css';
Using CSS Variables in React
1. In CSS / CSS Modules
/* Home.module.css */
.button {
background-color: var(--primary-color);
color: white;
padding: var(--padding);
border-radius: var(--border-radius);
font-size: var(--font-size);
}
import styles from './Home.module.css';
export default function Home() {
return <button className={styles.button}>Scoped Button</button>;
}
2. In Inline Styles
You can use them directly in React’s style={{}}
prop:
export default function Home() {
return (
<button
style={{
backgroundColor: 'var(--primary-color)',
padding: 'var(--padding)',
borderRadius: 'var(--border-radius)',
color: 'white',
}}
>
Inline Button
</button>
);
}
3. In Styled-Components
import styled from 'styled-components';
const Button = styled.button`
background-color: var(--primary-color);
color: white;
padding: var(--padding);
border-radius: var(--border-radius);
&:hover {
background-color: var(--secondary-color);
}
`;
export default function Home() {
return <Button>Styled Button</Button>;
}
4. Global vs Scoped CSS Variables
Type | Where? | Visibility | Example |
---|
Global | :root | Everywhere | :root { --main-color: blue; } |
Scoped | Inside selector or component | Only within that element and its children | .card { --card-bg: white; } |
Dynamic (React inline) | In style={{}} | Only for that element and its children | <div style={{ '--x': 'red' }}> |
Example of Scoped Variable
.card {
--card-padding: 20px;
padding: var(--card-padding);
}
<div class="card">
<p>Content inside card</p>
</div>
--card-padding
only works inside .card
Example of Dynamic Variable (React)
<div style={{ '--theme-color': 'purple' } as React.CSSProperties}>
<button style={{ backgroundColor: 'var(--theme-color)' }}>Dynamic Button</button>
</div>
Naming Conventions
:root {
/* Colors */
--primary-color: #2563eb;
--secondary-color: #10b981;
/* Spacing */
--padding-small: 8px;
--padding-large: 16px;
/* Typography */
--font-size-base: 16px;
--font-size-heading: 24px;
}
Summary
Use Case | How |
---|
Global values | Define in :root |
Component-specific | Define inside a selector |
Dynamic runtime | Define in React style={{ '--name': value }} |
Access anywhere | Use var(--name) |