What is a proper way to detect the support of css "flex-box" and "flex-wrap"?

how we can detect the support of css flex-box and flex-wrap by JavaScript.

Create an element and check the style property. If it is supported, it will return nothing i.e. '' else it will return undefined.

For example, if you run the below snippet in Chrome you will get undefined for columns and '' for flex-wrap.

Snippet:

console.log('flex = ' + document.createElement("p").style.flex);
console.log('columns = ' + document.createElement("p").style.columns);
console.log('flex-wrap = ' + document.createElement("p").style.flexWrap);

Although you have mentioned only Javascript in your question, but there is a CSS way of feature detection as well.

The @supports rule, also called CSS Feature Queries.

You provide the CSS declaration as the condition and the browser will execute that to return whether it supports or not. For example, the following CSS will apply green background color if flex is supported.

@supports (display: flex) {
  div { background-color: #0f0; }
}

The browser support is good amongst all modern browsers, barring IE (as usual). For IE and (Safari < 9), you will need to keep a fallback option when @supports rule fails.


Combining the above two, there is an API around that as well which you can use in Javascript to do feature detection.

var isColumnSupported = CSS.supports('columns', '');
console.log('columns supported: ' + isColumnSupported);

var isFlexWrapSupported = CSS.supports('flex-wrap', 'wrap');
console.log('flex-wrap supported: ' + isFlexWrapSupported);