Created
January 20, 2014 07:08
-
-
Save gutomarzagao/8516173 to your computer and use it in GitHub Desktop.
Polyfill for vw, vh, vm units. It calcutes the values in px and apply automatically to your css.
Credit for Lea Verou (https://gist.github.com/LeaVerou) and Xandor Schiefer (https://gist.github.com/zeorin)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Polyfill for the vw, vh, vm units Requires StyleFix from -prefix-free | |
| * http://leaverou.github.com/prefixfree/ | |
| * | |
| * @author Lea Verou | |
| * | |
| * Contributor: Xandor Schiefer | |
| * Contributor: Guto Marrara Marzagão | |
| * | |
| */ | |
| (function() { | |
| if (!window.StyleFix) { | |
| return; | |
| } | |
| // Feature test | |
| var dummy = document.createElement('_').style; | |
| var units = [ 'vw', 'vh', 'vm' ]; | |
| StyleFix.register(function(css) { | |
| var w = innerWidth, h = innerHeight, m = Math.min(w, h); | |
| // For help with this regex: see debuggex.com, then input: (/\*)?(-?\d+(\.\d+)?)(vw|vh|vm)(\*/)?(-?\d+(\.\d+)?px)? | |
| var regex = '(/\\*)?(-?\\d+(\\.\\d+)?)(' + units.join('|') + ')(\\*/)?(-?\\d+(\\.\\d+)?px)?'; | |
| return css.replace(RegExp(regex, 'gi'), function(match, notUsed1, originalValue, notUsed2, unit, notUsed3, notUsed4, notUsed5) { | |
| switch (unit) { | |
| case 'vw': | |
| var newValue = originalValue * w / 100; | |
| break; | |
| case 'vh': | |
| var newValue = originalValue * h / 100; | |
| break; | |
| case 'vm': | |
| var newValue = originalValue * m / 100; | |
| break; | |
| } | |
| return '/*' + originalValue + unit + '*/' + newValue + 'px'; | |
| }); | |
| }); | |
| var styleFixResizeTimer; | |
| window.addEventListener('resize', function () { | |
| if (typeof styleFixResizeTimer !== 'undefined') | |
| clearTimeout(styleFixResizeTimer); | |
| styleFixResizeTimer = setTimeout(function () { | |
| StyleFix.process(); | |
| }, 200); | |
| }, false); | |
| })(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment