Local Variables
Part of the Practical Frontend section of Coddy's HTML journey — lesson 4 of 35.
You may have noticed we often use :root to declare variables. This is because :root is global — variables defined here apply to the whole HTML page (as we mentioned before).
But sometimes, you want variables that only affect certain parts of the page. For example, imagine building an online shop with many product cards. You can create variables inside a .card class to style just those cards without affecting other elements.
.card {
--card-color: orchid;
background-color: var(--card-color);
}This way, the variable only works inside .card elements, giving you more control over specific areas.
Challenge
EasyYou are given an online shop page with several product cards. Your task:
- Inside the
.cardclass, create a local CSS variable named--card-accentand set its value tocoral. - Use this variable to set the text color of the
<h3>heading inside the card. - Use the same variable as the background color for the card’s
<button>.
Cheat sheet
CSS variables can be defined locally within specific selectors, not just globally in :root. Local variables only apply to elements within that selector's scope.
.card {
--card-color: orchid;
background-color: var(--card-color);
}This creates a variable --card-color that only works inside .card elements, providing more targeted control over styling specific components.
Try it yourself
<html>
<head>
<title>Local Variables</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Playfair+Display:ital,wght@0,400..900;1,400..900&display=swap" rel="stylesheet"> <style>
/* Global variable for body background */
:root {
--body-bg: #000f26;
--font-family: "Playfair Display", serif;
}
body {
background-color: var(--body-bg);
font-family: var(--font-family);
padding: 20px;
display: flex;
gap: 20px;
justify-content: center;
}
/* Card styles */
.card {
--card-bg: white;
background-color: var(--card-bg);
border-radius: 10px;
padding: 15px;
width: 250px;
text-align: center;
box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}
.card h3 {
margin-top: 0;
}
.card p {
font-size: 0.9rem;
color: #333;
}
.card button {
border: none;
color: #000f26;
padding: 8px 12px;
border-radius: 5px;
cursor: pointer;
font-weight: bold;
margin-top: 10px;
width: 100%;
}
</style>
</head>
<body>
<div class="card">
<h3>Classic Sneakers</h3>
<p>Comfortable and stylish sneakers for everyday wear.</p>
<button>Buy Now</button>
</div>
<div class="card special">
<h3>Luxury Watch</h3>
<p>Elegant watch with a unique design for special occasions.</p>
<button>Buy Now</button>
</div>
<div class="card">
<h3>Leather Backpack</h3>
<p>Durable, spacious backpack made from premium leather.</p>
<button>Buy Now</button>
</div>
</body>
</html>This lesson includes a short quiz. Start the lesson to answer it and track your progress.