[!NOTE] Modern Web Note: Modernizr was essential during the transition to HTML5 and CSS3. Modern development typically relies on
@supportsin CSS and direct API checking ('fetch' in window) in JavaScript.
Modernizr detects the availability of next-generation HTML5 and CSS3 features in the user's browser, replacing brittle user-agent sniffing with reliable feature detection.
How Modernizr Works
When loaded, Modernizr runs feature tests and:
- Adds classes like
.flexboxor.no-flexboxto the<html>root element. - Exposes a global
ModernizrJavaScript object with boolean test properties.
<script src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js"></script>
Conditional Styling in CSS
Target supported vs unsupported browsers directly in stylesheets:
/* Fallback layout for older browsers */
.no-flexbox .container {
display: block;
float: left;
}
/* Modern flexbox layout */
.flexbox .container {
display: flex;
justify-content: space-between;
}
JavaScript Feature Detection
if (Modernizr.geolocation) {
navigator.geolocation.getCurrentPosition(showMap);
} else {
showAddressInputFallback();
}
if (Modernizr.localstorage) {
localStorage.setItem('theme', 'dark');
}
if (Modernizr.webgl) {
initialize3DCanvas();
}
Common Detectable Features
CSS Features
flexbox,cssgridopacity,rgba,hslaboxshadow,textshadow,borderradiuscssanimations,csstransforms,csstransforms3d,csstransitionsbackgroundsize,borderimage,fontface
HTML5 & Storage APIs
canvas,canvastext,webgllocalstorage,sessionstorage,indexeddbgeolocation,history,websockets,webworkersvideo,audio,svg,inlinesvg