One popular programming principle is D.R.Y., which stands for Don’t Repeat Yourself. This simple yet powerful rule helps keep your code clean and efficient. It emphasizes that if you’re repeating the same instruction in different parts of your code, it’s time to consolidate that logic into one place.
The D.R.Y. principle isn’t just for programming logic—it applies to CSS too! Let’s explore how CSS variables can help you follow this principle.
Why CSS Variables?
Imagine you’ve written some CSS like this:
section {
height: 60px;
width: 60px;
}
In this case, both height and width share the same value. Instead of repeating these values everywhere, you can use CSS variables to streamline your code.
Creating CSS Variables
There are two ways to create CSS variables:
- Using the — prefix method
- Using the @property rule method
Using the — Prefix
This is the most common method. You define a variable by starting with double dashes (–), followed by a name of your choice, and then assign it a value. For example:]
article {
--banana: #fcc603;
}
Alternatively, you can define it globally in the :root pseudo-class, making it accessible throughout your document:
:root {
--banana: #fcc603;
}
- Element-specific variable: The variable applies only to the element and its children.
- Global variable: The variable applies to all elements in the DOM tree.
Using the @property Rule
The @property rule provides more control over your CSS variables. Here’s an example:
@property --apples-color {
syntax: "";
inherits: true;
initial-value: green;
}
Key points:
- syntax: Defines the type of value (e.g., <color>, <length>).
- initial-value: Specifies a default value.
Note: Both syntax and initial-value are required when using @property.
Using CSS Variables with the var() Function
To apply a CSS variable, use the var() function. Here’s how:
console.log( 'Code is Poetry' );@property --car-height {
syntax: "";
inherits: false;
initial-value: 100px;
}
article {
--banana: #fcc603;
}
.a-cool-child {
height: var(--car-height);
background-color: var(--banana);
}
In this case, if –car-height is unavailable, it will default to 600px.
And that’s the basics of CSS variables! They’re a handy tool for writing cleaner, more maintainable CSS. If you have any questions or feedback, drop a comment below. Let’s keep the conversation going!
Ready to take the plunge into the world of technology? Consider enrolling in the Fellowship program at The Bulb Africa. Our program offers comprehensive courses and guidance, helping you kickstart your career with confidence.