Categories
blog

CSS Custom Properties

Content Management

What is CSS Custom Properties?

CSS custom properties, also known as CSS variables, are personal customized values that can be created, stored and reused throughout the CSS stylesheet. CSS custom properties allow you to store a value in :root pseudo class or any other element, and then use it as a reference in multiple places, making it easier to maintain and update your styles. For example, CSS custom properties can help you in updating branding colors just once, and all of the pages where you have used the color will be updated.

Custom properties are declared using the--syntaxand are set on a specific element or a parent element in the stylesheet.

For example:

Source: CSS Tricks

and…

:root {
  --main-color: green;
}

p {
  color: var(--main-color);
}

In this example, the custom property --main-color is defined on the :root selector and set to green. The var() function is then used to reference the value of --main-color in the color property of the p selector.

How to declare custom property in CSS:

A custom property in CSS is declared using the-- syntax, followed by the property name and its value. The custom property can be declared on any CSS selector, but it is recommended to define it on a parent element such as :root or a specific class, so that it can be reused throughout the stylesheet.

Here is an example of declaring a custom property on the :root selector:

Source: CSS Tricks

Correct ways to declare custom property:

Source: CSS Tricks

Note: CSS Custom Properties are case sensitive and use of special characters is not allowed in it.

Using properties as properties:

You can use one custom property inside another custom property in CSS. This can be useful for creating reusable values and themes, as well as for reducing repetitive code.

Here’s an example of using a custom property inside another custom property:

Source: CSS Tricks

Which browsers support custom properties?

Custom properties are supported in almost most of the mordern browsers, including Chrome, Firefox, and Edge. However, browsers like Opera mini do not support custom properties, so it is suggested to check the compatibility of your target audience’s browsers before using them.

Source: caniuse.com

Use cases of custom properties:

Benefits of using custom property:

  1. Scoping: (They help DRY up your CSS.That is “Don’t Repeat Yourself.” – CSS Tricks) Custom properties can make code easier to maintain because you can update one value and have it reflected in multiple places.
  2. Inheritance: Custom properties are inherited, so if you declare a custom property on a parent element, its value will be inherited by its descendants.
  3. Dynamic updates: Custom properties can be updated dynamically using JavaScript, which makes it easy to create themes or switch between different styles. For example, colour themes of LIGHT & DARK MODE.

Splitting up colours using custom properties:

You can split up colors into separate components using custom properties in CSS. For example, you could declare separate custom properties for the red, green, and blue (RGB) values of a color, or for the hue, saturation, and lightness (HSL) values of a color.

Here’s an example of splitting up an RGB color into separate custom properties:

:root {
  --red: 255;
  --green: 153;
  --blue: 51;
}

body {
  background-color: rgb(var(--red), var(--green), var(--blue));
}

In this example, three custom properties of color values in RGB are declared in the :root selector: and those are --red--green, and --blue. The HTML element body declares the background-color property and uses the CSS custom properties as the RGB value of 255, 153, 51.

Here’s an example of splitting up an HSL color into separate custom properties:

Source: CSS Tricks (Example on how to use custom properties in CSS)
Result of the code displayed above.

Shadows through custom properties:

You can also use custom properties in CSS to define reusable shadow values. Shadows are often used to add depth and dimension to elements, and by defining the shadow values as custom properties, you can easily update and reuse them throughout your stylesheet.

Here’s an example of using custom properties for box shadows:

:root {
  --shadow-color: rgba(0, 0, 0, 0.2);
  --shadow-offset-x: 0;
  --shadow-offset-y: 2px;
  --shadow-blur: 4px;
}

.box {
  box-shadow: var(--shadow-offset-x) var(--shadow-offset-y) var(--shadow-blur) var(--shadow-color);
}

In this example, four custom properties are declared on the :root selector: --shadow-color--shadow-offset-x--shadow-offset-y, and --shadow-blur. The box-shadow property of the .box selector uses the var() function to reference the values of these custom properties, setting the box shadow of all elements with the .box class.

It does not require to write the whole property again, as shown in the example below:

Source: CSS Tricks
Result of the code displayed above.

Use of custom property with @media queries:

Media queries don’t change specificity, but they often come later (or lower) in the CSS file than where the original selector sets a value, which also means a custom property will be overridden inside the media query.

This type of example is very useful in creating light and dark modes for websites.

Custom property with !important:

You can use the !important flag with custom properties, just like with any other CSS property. However, it is generally considered a best practice to avoid using !important as much as possible, as it can make your stylesheet more difficult to maintain and can lead to unexpected results.

Here’s an example of using a custom property with the !important flag:

NOTE: The !important function does not depend on specifity or cascading effect.

another example…

Source: CSS Tricks

:root {
  --background-color: green;
}

body {
  background-color: var(--background-color) !important;
}

.highlight {
  background-color: yellow !important;
}

In this example, a custom property --background-color is declared on the :root selector with a value of green. The background-color property of the body selector uses the var() function to reference the value of the custom property, and sets the background color of the body element to green.

The .highlight class sets the background-color property to yellow, using the !important flag to ensure that this value takes precedence over any other styles that might have been applied to the element.

Using calc( ) with custom property:

You can use the calc() function with custom properties (also known as CSS variables) in CSS. This allows you to perform calculations based on the value of a custom property, and use the result as a value for another property. Here’s an example:

Source: CSS Tricks
Result of the code displayed above.

In this example, we’ve declared a custom property named --spacing with a value of 10px on the :root pseudo-class. Then, in the .element class, we’re using the calc() function to calculate the value of the padding property based on the value of --spacing. The var() function is used to retrieve the value of the custom property. In this case, the padding value will be 20px, which is equal to 10px*2.

Using @property with custom properties:

In CSS, the @property feature allows authors to use JavaScript to create custom properties that can be used in CSS. It’s sort of like you’re creating an actual CSS property and have the ability to define what it’s called, it’s syntax, how it interacts with the cascade, and its initial value.

Source: CSS Tricks

This code defines a custom property, --r, and uses it to rotate an HTML element with the class .star.

The @property directive is used to define custom properties, which can be used to store and reuse values in CSS. In this case, the --r property is defined with the following attributes:

  • inherits: false; Indicates that the property value should not be inherited by child elements.
  • initial-value: 0deg; Sets the initial value of the property to 0deg.
  • syntax: “<angle>”; Specifies that the value of the property must be an angle.

The .star class uses the --r property to rotate the element. The transform property is set to rotate(var(–r)), which rotates the element by the value of the --r property.

The element is animated using the animation property, with the spin keyframe animation. The spin keyframe animation has a single keyframe, 100%, that sets the value of the --r property to 360deg, causing the element to rotate 360 degrees over the course of 1 second. The animation is set to repeat indefinitely with the infinite value.

Custom properties with JavaScript:

Using custom properties with JavaScript involves accessing the custom properties using the style property of an element and setting new values for the custom properties using the setProperty() method. Here is the general syntax for accessing and updating custom properties in JavaScript:

IMAGE 1
IMAGE 2

In the code mentioned in image 2, the first line retrieves the value of a custom property named “–my-var” from the inline style of an HTML element. Inline styles are styles that are applied directly to the element using the style attribute.

The second line retrieves the value of the same custom property, but from wherever it is defined. This can include stylesheets, styles applied via JavaScript, and other sources. The getComputedStyle function returns the final computed values of all the CSS properties applied to the element, including custom properties.

The third line sets the value of the “--my-var” custom property on the inline style of the element. The setProperty method allows you to set or update the value of any CSS property, including custom properties. In this case, the new value is a JavaScript variable named jsVar plus the number 4.

Overall, this code is useful for manipulating and updating CSS custom properties dynamically using JavaScript. By using custom properties, you can create more flexible and reusable styles that can be easily updated and customized.

<div class="mover"></div>

HTML

let root = document.documentElement;

root.addEventListener("mousemove", e => {
  root.style.setProperty('--mouse-x', e.clientX + "px");
  root.style.setProperty('--mouse-y', e.clientY + "px");
});

JavaScript

.mover {
  width: 50px;
  height: 50px;
  background: red;
  position: absolute;
  left: var(--mouse-x);
  top: var(--mouse-y);
}

CSS

Try the code mentioned here for better understanding.

Source: CSS Tricks

Things to keep in mind while using Custom properties:

1. Create fallback values for your custom property:

Fallback values: Fallback values are required if your CSS properties don’t work.

You can provide a fallback value to the var() function in case the custom property is not defined, or the browser doesn’t support custom properties.

2. Effects of cascading on custom properties:

The rules of cascading in CSS, just like any other property, are also applied to CSS Custom Properties. This means that the value of a custom property is overridden by another custom property with the same name but a different value, which is written later.

Source: CSS Tricks

Conclusion:

Your code can be consistent, modular and reduced to a certain extent with CSS Custom Properties. It is majorly helpful in websites which has a lot of pages and helps in reducing typing the code throughout those pages. It is simple to use and helps you in making your CSS more efficient.

PPT Link:

https://docs.google.com/presentation/d/10O8WEpvXBywfLEJytTW4k9qdsgGRO9-T/edit?usp=sharing&ouid=116356089149123243975&rtpof=true&sd=true

References:

  1. CSS Tricks: https://css-tricks.com/a-complete-guide-to-custom-properties/

2. Browser Support: https://caniuse.com/?search=css%20custom%20properties

3. ChatGPT: For code snippets, like,

1. Splitting up colors using custom properties:

body {
  background-color: rgb(var(--red), var(--green), var(--blue));
}


2. Shadows through custom properties:

.box {
  box-shadow: var(--shadow-offset-x) var(--shadow-offset-y) var(--shadow-blur) var(--shadow-color);
}

Leave a Reply

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