Global Scope
: Variables defined at the
:root
level are considered to be in the
global
scope and can be
accessed
throughout your
entire stylesheet.
Example1:
CSS:
:root {
--primary-color: #007bff; /* Define the CSS variable */
}
.button {
background-color: var(--primary-color); /* Use the CSS variable */
}
HTML:
<button class="button">Button 1</button>
<button class="button">Button 2</button>
<button class="button">Button 3</button>
Example2:
:root {
--card-bg-color: #232323;
--text-color: #7FFFD4;
--text-font-family: 'Arial', sans-serif;
--text-font-size: 17px;
--text-line-height: 1.5;
}
.card {
border: 1px solid #ddd;
padding: 20px;
margin: 10px;
background-color: var(--card-bg-color);
}
.card p {
color: var(--text-color);
font-family: var(--text-font-family);
font-size: var(--text-font-size);
line-height: var(--text-line-height);
}
HTML:
<div class="card">
<p>This is the first card. Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</div>
<div class="card">
<p>This is the second card. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris.</p>
</div>
<div class="card">
<p>This is the third card. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.</p>
</div>
Example 3:
CSS:
:root {
--color-white: #ffffff;
--color-blue: #007bff;
--color-red: #ff0000;
--color-green: #00ff00;
--color-yellow: #fcba03;
}
.card {
background-color: #f8f8f8;
border: 5px solid var(--color-yellow);
padding: 20px;
margin: 10px;
}
.card h2 {
color: var(--color-blue);
}
.card p {
color: var(--color-black);
}
.button {
background-color: var(--color-red);
color: var(--color-white);
padding: 10px 20px;
border: none;
cursor: pointer;
margin: 5px;
}
HTML:
<div class="card">
<h2>Card 1</h2>
<p>This is some text within Card 1.</p>
<button class="button">Button 1</button>
</div>
<div class="card">
<h2>Card 2</h2>
<p>This is some text within Card 2.</p>
<button class="button">Button 2</button>
</div>
<div class="card">
<h2>Card 3</h2>
<p>This is some text within Card 3.</p>
<button class="button">Button 3</button>
</div>