0
0
CSSmarkup~20 mins

Variable scope in CSS - Mini Project: Build & Apply

Choose your learning style9 modes available
Understanding CSS Variable Scope
📖 Scenario: You are creating a simple webpage with two sections. Each section should have a different background color using CSS variables. You will learn how CSS variables can be defined globally and locally, and how their scope affects the colors shown.
🎯 Goal: Build a webpage with two sections. Use a global CSS variable for the background color of the first section. Then, override that variable locally inside the second section to change its background color. This will show how CSS variable scope works.
📋 What You'll Learn
Create a global CSS variable --main-bg-color with the value #a0d8f1.
Use the global variable --main-bg-color to set the background color of the first section.
Inside the second section, override the --main-bg-color variable with the value #f1a0a0.
Use the overridden variable to set the background color of the second section.
Use semantic HTML elements and ensure the page is responsive.
💡 Why This Matters
🌍 Real World
CSS variables help web developers manage colors and styles consistently across a website. Understanding scope lets you customize parts of a page without repeating code.
💼 Career
Knowing CSS variable scope is important for front-end developers to write clean, maintainable, and scalable stylesheets.
Progress0 / 4 steps
1
Create the HTML structure with two sections
Write the HTML code to create a <main> element containing two <section> elements with class names section1 and section2. Each section should have a heading: <h2>Section 1</h2> and <h2>Section 2</h2> respectively.
CSS
Need a hint?

Use semantic tags: <main> for the main content and <section> for each part.

2
Define a global CSS variable for background color
In the CSS, create a :root selector and define a CSS variable called --main-bg-color with the value #a0d8f1.
CSS
Need a hint?

The :root selector is used to define global CSS variables.

3
Use the global variable for the first section's background
Add CSS to set the background color of .section1 using the global CSS variable --main-bg-color.
CSS
Need a hint?

Use var(--main-bg-color) to access the CSS variable.

4
Override the variable locally for the second section
Inside the CSS for .section2, override the --main-bg-color variable with the value #f1a0a0. Then set the background color of .section2 using the overridden variable.
CSS
Need a hint?

Override the variable by declaring it inside .section2 and then use var(--main-bg-color) for the background color.