HTML & CSS · Beginner · 15 min
Reuse colors with CSS variables
Define a custom property and reuse its value in several styles.
Name a reusable color
A custom property stores a reusable CSS value. Its name starts with two hyphens, such as --accent. Define it on a shared container, then read it with var(--accent). This keeps a heading and a border tied to one color.
<style>
.theme { --accent: #1d4ed8; }
.theme h1 { color: var(--accent); }
.card { border: 2px solid var(--accent); }
</style>
<main class="theme">
<h1>My projects</h1>
<article class="card">A walking route</article>
</main>Expected appearance
h1 color: rgb(29, 78, 216) border-color: rgb(29, 78, 216)
Override a value locally
Custom properties declared this way pass from a parent to its children. A child can override --accent for its own subtree without changing a sibling. Names are case-sensitive. In var(--accent, navy), navy is a fallback if --accent has not been defined.
<style>
.theme { --accent: #1d4ed8; }
.special { --accent: teal; }
h2 { color: var(--accent, navy); }
</style>
<div class="theme">
<section><h2>Study notes</h2></section>
<section class="special"><h2>Weekend walk</h2></section>
</div>Expected appearance
Study notes: rgb(29, 78, 216) Weekend walk: rgb(0, 128, 128)
Try it yourself
Code runs on this device. When you are signed in, drafts sync to your account.
Edit the page content and include CSS in a style element. The preview supports a limited set of HTML elements. Scripts, external resources, navigation to other sites, and form submission are disabled.
Build and check
Keep the supplied HTML. Set --accent: #1d4ed8 on .theme. Use color: var(--accent) for its <h1>. Give both .card elements border: 2px solid var(--accent) and padding: 16px.
Put --accent on .theme so the heading and cards inherit it. Use color: var(--accent) and border: 2px solid var(--accent).
Show worked solution
<style>
main { font-family: sans-serif; line-height: 1.5; }
.card { margin-bottom: 16px; }
.theme { --accent: #1d4ed8; }
.theme h1 { color: var(--accent); }
.card { border: 2px solid var(--accent); padding: 16px; }
</style>
<main class="theme">
<h1>My projects</h1>
<article class="card"><h2>Weekend walk</h2><p>A route through the park.</p></article>
<article class="card"><h2>Study notes</h2><p>Ideas from this week.</p></article>
</main>Both rules read --accent from .theme. Changing that one value updates the heading and both borders.
Page preview
Run to preview your page. Check tests the task requirements, including the requested screen widths. Check results do not replace keyboard and visual review.
Try it yourself
- Complete the task, then change only --accent to teal and preview the page. The heading and both borders should change together.
- Restore #1d4ed8 before checking the original task again.