Skip to content

Instantly share code, notes, and snippets.

@davidhund
Last active June 29, 2024 13:49
Show Gist options
  • Save davidhund/b995353fdf9ce387b8a2 to your computer and use it in GitHub Desktop.
Save davidhund/b995353fdf9ce387b8a2 to your computer and use it in GitHub Desktop.
The simplest feature-detect for flexbox?
/*
* Trying to feature-detect (very naive)
* CSS Flexbox support.
* - Only most modern syntax
*
* Is this nonsense?
*/
(function NaiveFlexBoxSupport(d){
var f = "flex", e = d.createElement('b');
e.style.display = f;
return e.style.display == f;
})(document);
@Webnewbies
Copy link

Webnewbies commented Aug 22, 2016

Thank's for you help. I wrote this code for you:

(function(d) {
        'use strict';
        var c = " ", prefixFlex = 'flex -webkit-flex -ms-flexbox -moz-box -webkit-box'.split(' '), elem = d.createElement('b'), mStyle = elem.style;
        try {
            for (var i = 0, len = prefixFlex.length; i < len; i++) {
                c += ( (mStyle.display = prefixFlex[i]) && mStyle.display != prefixFlex[i] ) ? 'no-flex' :  'flex', (i = len);
            }
        } catch(e) { 
            c += "no-flex";
        }
        d.documentElement.className =  c + 'box';
    })(document);

@brentonstrine
Copy link

Just curious in what circumstances this will cause an error. I'm assuming it can cause an error since you added the try/catch block.

@kingsloi
Copy link

@ergcode
Copy link

ergcode commented Aug 25, 2017

David, how about this solution?
https://github.com/ergcode/ergonomic.detect_flex

@jblok
Copy link

jblok commented Sep 12, 2017

Wrote a version of Davids script that returns a boolean

export const testFlexbox = () => {
  const f = 'flex';
  const fw = `-webkit-${f}`;
  const el = document.createElement('b');

  try {
    el.style.display = fw;
    el.style.display = f;
    return !!(el.style.display === f || el.style.display === fw);
  } catch (err) {
    return false;
  }
};

@mcshaman
Copy link

Or you could make it css property generic

function cssPropertySupported(pNames) {
	const element = document.createElement('a')

	let index = pNames.length

	try {
		while (index--) {
			const name = pNames[index]

			element.style.display = name
			if (element.style.display === name) {
				return true
			}
		}
	} catch (pError) {}

	return false
}

cssPropertySupported(['-webkit-box', '-ms-flex', 'flex'])

@patrick-fischer-hirschstein

according to mcshaman post:

cssPropertySupported(['-webkit-box', '-ms-flex', 'flex'])

should be:
cssPropertySupported(['-ms-flexbox', '-webkit-box', 'flex'])

By the way:

return true

should be:
return name

so you know what syntax is used

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment