in

How to use CSS variables like a pro

programmer coding with huge template b on screen behind him

[ad_1]

CSS variables, also known as custom properties, can be used to minimize repetition in style sheets. This saves time and effort when making design changes. Also, you won’t miss a value that needs to be updated.


Once you access the DOM, you can create variables, store them, and reuse them throughout your stylesheet.


How CSS variables are defined and used

To make your style sheets more organized, easier to maintain, and easier to reuse, any property that accepts a value can make use of CSS variables.

Here’s an example HTML and CSS file that doesn’t use CSS variables.

HTML:

 <!DOCTYPE html>
<html lang="en">
  <head>
    <title>CSS Variables - Button Variations</title>
    <link rel="stylesheet" href="Variables.css" />
  </head>
  <body>
    <div>
      <h1>CSS Variables</h1>
      <div>
        <button class="btn sub-primary">Primary</button>
        <button class="btn">Secondary</button>
      </div>
    </div>
  </body>
</html>

CSS:

 .btn {
  padding: 1rem 1.5rem;
  background: transparent;
  font-weight: 700;
  color: red;
}

The page looks like this:

Screenshot of two buttons styled red with CSS

of .btn The classes used in the style sheet above are not dynamic, so you’ll need to create separate classes to customize each individual button. To create a beautiful website, the front-end style should be dynamic. Implementing a button like this makes it cumbersome to accomplish that task.

As with most programming languages, CSS variables need to be initialized and replaced.

To initialize a CSS variable, prefix the variable name with two hyphens.

 :root{
}

Note that variables can be initialized anywhere, but only within the initialized selector. For this reason, CSS variables are usually initialized inside the root selector. It targets the top-level element of the DOM and allows you to access variables throughout the HTML document on a global scale.

To replace variables with CSS styles, var() property:

 :root {
  
  --primary:
  --secondary:
}

.btn {
  padding: 1rem 1.5rem;
  background: transparent;
  font-weight: 700;
  color: var(--primary);
  background-color: var(--secondary);
}

.sub-primary {
  color: var(--secondary);
  background-color: var(--primary);
}

A route selector contains two variables. – Major When –secondary. Then both variables are .btn classes as color and background color respectively.

Variables make it easier to style individual elements. By reusing variables, you can quickly change the value once and have it updated in all instances.

Screenshot of two buttons styled with different colors using CSS variables

of var() Properties can also take a second argument. This argument serves as a fallback value for the first argument in situations where the first argument is undefined or invalid.

for example:

 :root {
  --primary:
  --secondary:
}

.btn {
  padding: 1rem 1.5rem;
  background: transparent;
  font-weight: 700;
  color: var(--primary, blue);
}

In this example, – Major to a variable colour style. If for some reason this value fails, the stylesheet will use her second value as a fallback. You can also use another CSS variable as a fallback value.

Manipulating and Overriding CSS Variables with JavaScript

Using JavaScript to manipulate CSS variables is a powerful way to change the look and feel of your website on the fly. You can use JavaScript to update the values ​​of these variables and see the changes reflected on your site.

Note that changes made in JavaScript apply only to the current session. To make changes permanent, you need to update the original source or store the new value on the client like a cookie.

Here’s an example of how to update the value of a CSS variable using JavaScript.

HTML:

 <!DOCTYPE html>
<html lang="en">
  <head>
    <title>CSS Variables - Button Variations</title>
    <link rel="stylesheet" href="Variables.css" />
    <script>
    function changeColor() {
      
      const myElement = document.querySelector(":root");

      
      let currentValue = getComputedStyle(myElement).getPropertyValue(
        "--secondary"
      );

      // Set the new value for the variable
      myElement.style.setProperty("--secondary"https://news.google.com/__i/rss/rd/articles/,"#DAF7A6");
    }
    </script>
  </head>
  <body>
    <div>
      <h1>CSS Variables</h1>
      <div>
        <button class="btn sub-primary" onclick="changeColor()">
         Primary
       </button>
        <button class="btn">Secondary</button>
      </div>
    </div>
  </body>
</html>

CSS:

 :root {
  --primary:
  --secondary:
}

.btn {
  padding: 1rem 1.5rem;
  background: transparent;
  font-weight: 700;
}

.sub-primary {
  color: var(--primary);
  background-color: var(--secondary);
}

In this JavaScript code, change color () The function updates the color of the first button when the user clicks it.

You can use DOM traversal methods to access classes or selectors applied to the HTML document and manipulate their values.

Before clicking the button:

Screenshot of the two buttons.One of them is styled with a CSS variable

After clicking the button:

Screenshot of the two buttons.One of them used JavaScript and CSS variables to style the white

You can also use JavaScript to create new CSS variables or remove them entirely.

for example:

 // Create a new variable
document.documentElement.style.setProperty('--new-color', 'blue');


document.documentElement.style.removeProperty('--new-color');

Using CSS variables in preprocessors

The use of variables within front-end technologies was first achieved with CSS preprocessors such as: SASS, LESS, and Stylus.

The purpose of CSS preprocessors is to develop code that extends the basic functionality of standard CSS. It then compiles that code into standard CSS for browsers to understand.

With the development of CSS variables, preprocessors have become less important, but they can still provide some use when combined with CSS variables in your project.

SASS variables can be defined $ main color Use it to set the value of a CSS variable. Then use the CSS variable in your regular style class.

You can also use SASS functions to manipulate the values ​​of CSS variables.

for example:

 :root {
  --primary: $main-color;
  --secondary: lighten(var(--primary), 20%);
}

.btn {
  color: var(--primary);
  background-color: var(--secondary);
}

where the SASS function Brighten() operate on the value of – Major get the value of –secondary.

Note that SASS variables are not accessible from JavaScript. Therefore, if you need to manipulate the value of a variable at runtime, you should use CSS variables.

Using CSS variables and preprocessors together gives you the best of both worlds, including powerful preprocessor features such as loops and functions, and CSS variable features such as CSS cascading.

Tips for using CSS variables in web development

Here are some important tips to make better use of CSS variables.

Start with a clear naming convention

Choose a naming convention that makes variables easy to understand and use. For example, using prefixes like: – colour- color variable or –interval- for interval variables.

Using variables in media queries

Using variables in media queries makes it easy to adjust your design for different screen sizes.

Take advantage of the cascading nature of CSS

Note that CSS variables are cascading. In other words, setting a variable on a parent element affects all its children.

Use CSS variables with care

Using too many CSS variables can be confusing, so use them sparingly and only when it makes sense and makes your code more maintainable.

test the variable

CSS variables are a unique way to write clear, maintainable code within your style sheets.

Please note that it is not yet fully supported by all browsers. Therefore, you should test your variables for browser compatibility to ensure that they work as expected and fallback values ​​work as expected.

[ad_2]

Source link

What do you think?

Leave a Reply

Your email address will not be published. Required fields are marked *

GIPHY App Key not set. Please check settings

    EnergyAspects

    Energy Aspects Acquires OilX, Pioneer of AI-Driven Data Analytics for Energy Markets

    IMG 0772

    CSS Church’s Day School: A Community Oriented Place for All Children