DEV Community

Rova Ranaivo
Rova Ranaivo

Posted on

20

CSS's :root Variables. Use it!

CSS's :root selector lets you define global variables that can be used in your stylesheets. These variables, also known as custom CSS properties, provide a convenient way of storing and reusing values, making your stylesheets more modular and easier to maintain.

1. Defining :root variables

To define a :root variable, use the :root selector followed by the variable name and value, surrounded by double dashes (--).
Here is an example:

:root {
  --primary-color: #fff;
  --font-size: 14px;
}
Enter fullscreen mode Exit fullscreen mode

2. Using :root Variables

To use a :root variable, you can refer to it using the var() function and the variable name, as following:

body {
  color: var(--primary-color);
  font-size: var(--font-size);
}
Enter fullscreen mode Exit fullscreen mode

3. Overriding :root Variables

You can override :root variables at any point in your stylesheets by redefining them. This flexibility allows you to update the variable value globally, affecting all the styles that rely on it.

4. Benefits of :root Variables

  • Reusability: Use variables throughout your stylesheets, reducing code duplication.
  • Consistency: Maintain a consistent look and feel by centralizing values in variables.
  • Dynamic Updates: Change variable values dynamically, resulting in global style changes.

Conclusion:
Using :root variables in CSS is a powerful way of defining and reusing values in your style sheets. By centralizing your values and making them easily modifiable, you can improve code maintenance, achieve consistent styling and create more flexible designs.

Remember to update your stylesheets to take advantage of :root variables and enjoy the benefits they provide in your CSS development process.

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (1)

Collapse
 
moinulmoin profile image
Moinul Moin

Awesome work, Rova. Keep it up!

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay