DEV Community

Cover image for Powerful @property 🔥
Alwar G
Alwar G

Posted on

Powerful @property 🔥

After reading the wonderful post by @una, I know what is @property in CSS?

    First of all, it's a CSS Houdini custom property. If you don't know what is CSS Houdini, then read this first.

ok, let's start.

CSS syntax:

// For Chromium 85 and above
  @property --MyColor {
    syntax: '<color>';
    initial-value: red;
    inherits: false;
  }
Enter fullscreen mode Exit fullscreen mode

     If your Chromium browser is from 78 and above and below 85, then you should include some javascript code to make this functionality to work.

Fallback JS code:

CSS.registerProperty({
  name: '--MyColor',
  syntax: '<color>',
  initialValue: 'red',
  inherits: false
});
Enter fullscreen mode Exit fullscreen mode

structure:

  • name - name of the property(eg: myColor, columnPercentage, etc...).
  • syntax - syntax of the property.
    Allowable values are

    1). length

    2). number

    3). percentage

    4). length-percentage

    5). color

    6). image

    7). url

    8). integer

    9). angle

    10). time

    11). resolution

    12). transform-list

    13). transform-function

    14). custom-ident

  • initial-value - Begining value of the property

  • inherits - Defines whether inherit the value from the parent or not

    After knowing this thing as a web developer, you might have the following question.

How it defers from normal CSS variables?🀔

    In the CSS variable, we can only give value. But using the @property, we can define the syntax like value should be in color.

So, we can write the code with a more semantical meaning 🔥.

Let's explore this property with the following Example

Note:

    We can able to overwrite the values in the particular block like below.

  @property --Mycolor {
  syntax: '<color>';
  initial-value: red;
  inherits: false;
}
.text {
  --Mycolor: blue;
  color: var(--Mycolor); // blue
}
Enter fullscreen mode Exit fullscreen mode

    If we give invalid value, then it will back off to the initial value. for example, if we give some number value(67) in the color property, then it will back off to the initial value(red).

.text {
  --Mycolor: 67;
  color: var(--Mycolor); // red
}
Enter fullscreen mode Exit fullscreen mode

I hope you enjoyed this post 😍. Thanks for reading.

Source Url: https://web.dev/at-property/

Latest comments (0)