Course Content
CSS Fundamentals
CSS Fundamentals
Effective Work with CSS
Variables
CSS variables, also known as CSS custom properties, provide a way to define reusable values throughout our CSS code. By utilizing variables, we can create dynamic and flexible designs that are easier to maintain and update.
To declare a variable, we use the :root
pseudo-class at the top of our CSS file and prefix the variable name with --
. For example, let's define a --blue-color
variable with the value #3f42f3
in our :root
block:
Once we have declared a variable, we can apply it to any CSS property using the var()
function. For instance, to assign the color
property of an <h1>
element the value of our --blue-color
variable, we can write:
Let's combine the knowledge of variable declaration and usage in the following example:
index
index
index
In this example, we define two variables, --background-color
and --text-color
, and apply them to the background-color
and color
properties, respectively. By changing the values of these variables, we can easily update the colors throughout the stylesheet.
Overriding Properties
Sometimes, we need to override specific properties in CSS to achieve the desired styling. This can be accomplished by declaring a property with the same name within a nested selector and assigning a new value.
Consider the following example of a traffic light with different color signals:
index
index
index
By targeting the specific signal classes, we can fine-tune the color for each signal while maintaining the shared styles defined in the base .signal
selector.
Note
In conclusion, CSS variables provide flexibility and maintainability, allowing for dynamic design updates, while overriding properties enables us to fine-tune styles and achieve the desired visual effects.
Everything was clear?