Thursday, April 11, 2019

Get a CSS Custom Property Value with JavaScript

Here’s a neat trick from Andy Bell where he uses CSS Custom Properties to check if a particular CSS feature is supported by using JavaScript.

Basically, he's using the ability CSS has to check for browser support on a particular property, setting a custom property that returns a value of either 0 or 1 (Boolean!) and then informing the JavaScript to execute based on that value.

Here's his example:

.my-component {
  --supports-scroll-snap: 0;
}

@supports (scroll-snap-type: x mandatory) {
  .my-component {
    --supports-scroll-snap: 1;
  }
}
const myComponent = document.querySelector('.my-component');
const isSnapSupported = getCSSCustomProp('--supports-scroll-snap', myComponent, 'boolean');

As Andy mentions, another common way to do this is to use pseudo elements on the body element and then access them with JavaScript, but this approach with @supports seems a whole lot cleaner and less hacky to me, personally. I wonder how many more intuitive things we’ll find we can do with CSS Custom Properties because this is an interesting case where CSS instructs JavaScript, instead of the other way around.

Direct Link to ArticlePermalink

The post Get a CSS Custom Property Value with JavaScript appeared first on CSS-Tricks.

from CSS-Tricks https://andy-bell.design/wrote/get-css-custom-property-value-with-javascript/

The following post Get a CSS Custom Property Value with JavaScript See more on: Instant Web Site Tools



source https://www.instant-web-site-tools.com/2019/04/11/get-a-css-custom-property-value-with-javascript/

No comments:

Post a Comment

40+ Best Minimal Logo Design Templates

Minimalist logo design is an art. How can you convey your brand with a professional logo, but keep the simplicity of a minimal, clean, and s...