How to check if css value is supported by the browser?

十年热恋 提交于 2019-11-28 21:15:24

I assume you meant to check whether the vh value is supported, not whether specifically DIV#id bears it?

function cssPropertyValueSupported(prop, value) {
  var d = document.createElement('div');
  d.style[prop] = value;
  return d.style[prop] === value;
}
cssPropertyValueSupported('width', '1px');
// => true
cssPropertyValueSupported('width', '1vh');
// => maybe true, maybe false (true for me)
cssPropertyValueSupported('width', '1foobar');
// => false
Eric Willigers

There is the new API CSS.supports. Supported in most browsers except IE.

console.log(
  // CSS.supports(property, value)
  1, CSS.supports("text-decoration-style", "blink"),
  2, CSS.supports("display", "flex"),
  3, CSS.supports('--foo', 'red'),
  4, CSS.supports('(--foo: red)'),

  // CSS.supports(DOMstring)
  5, CSS.supports("( transform-origin: 5% 5% )"),
  6, CSS.supports("( transform-style: preserve ) or ( -moz-transform-style: preserve ) or " 
  + "( -o-transform-style: preserve ) or ( -webkit-transform-style: preserve )")
)

And there is a similar feature in CSS, the @supports feature query selector, also supported in most browsers except IE:

@supports (display: grid) {
  div {
    display: grid;
  }
}
@supports not (display: grid) {
  div {
    float: right;
  }
}
Trevor Clarke

I see the code you have there.

var styletotest = "PutStyleHere";

if (styletotest in document.body.style)
{
    alert("The " + styletotest + " property is supported");

} else {

    alert("The " + styletotest + " property is NOT supported"); 

}

Simply place the css property you want to test in the quotes where it says

PutStyleHere

And when you load the file it will show a popup telling you if it works or not.

However this seems unnecessary.

Simply Googling:

[property] css W3

where [property] is the property you want to know browser support information.

When I searched

Opacity Css W3

and then clicked on the W3 link... you can scroll down and you will see a section of the page with the info you want like this:

Source

We can since a while test from javascript if a css rule if available in the context with CSS.supports.

(Since Firefox 22/ Chrome 28)

console.log(
CSS.supports("( transform-origin: 5% 5% )"),
"\n",
CSS.supports("( display: flex )"),
"\n ",
CSS.supports("( background-color: #12233212 )")
)

The CSS.supports() static methods returns a Boolean value indicating if the browser supports a given CSS feature, or not.

https://developer.mozilla.org/en-US/docs/Web/API/CSS/supports

I'd suggest to use Modernizr.

Modernizr is a JavaScript library that detects which HTML5 and CSS3 features your visitor's browser supports. In detecting feature support, it allows developers to test for some of the new technologies and then provide fallbacks for browsers that do not support them.

Some useful links:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!