-
-
Save LeaVerou/1347501 to your computer and use it in GitHub Desktop.
| /** | |
| * Polyfill for the vw, vh, vm units | |
| * Requires StyleFix from -prefix-free http://leaverou.github.com/prefixfree/ | |
| * @author Lea Verou | |
| */ | |
| (function() { | |
| if(!window.StyleFix) { | |
| return; | |
| } | |
| // Feature test | |
| var dummy = document.createElement('_').style, | |
| units = ['vw', 'vh', 'vm'].filter(function(unit) { | |
| dummy.width = ''; | |
| dummy.width = '10' + unit; | |
| return !dummy.width; | |
| }); | |
| if(!units.length) { | |
| return; | |
| } | |
| StyleFix.register(function(css) { | |
| var w = innerWidth, h = innerHeight, m = Math.min(w,h); | |
| return css.replace(RegExp('\\b(\\d+)(' + units.join('|') + ')\\b', 'gi'), function($0, num, unit) { | |
| switch (unit) { | |
| case 'vw': | |
| return (num * w / 100) + 'px'; | |
| case 'vh': | |
| return num * h / 100 + 'px'; | |
| case 'vm': | |
| return num * m / 100 + 'px'; | |
| } | |
| }); | |
| }); | |
| })(); |
Neat, thanks for sharing! But what’s the vm unit? The specs (to-date) describe vw (viewport width), vh (viewport height), but no vm.
There are instead vmin (the smaller of vw or vh) and vmax (the larger of vw or vh).
Being able to declare an element’s width and/or height conditionally as minimally (or maximally) a percentage of either the viewport’s height or it’s width, whichever is the smallest (or biggest), can be very useful for responsive design, esp. reckoning with device orientation, m.m. portrait/landscape.
@LeaVerou — Is this polyfill being developed any further?
I found this implementation by @saabi to be somewhat more up-to-date (albeit much more heavy). (And it has an impressive demo!) ⟶ https://github.com/saabi/vminpoly
what do you mean stylefix???
Is there any standalone one?
Only Integer values are covered not float values like 3.25vw
@zeorin do you have a demo I could check out? I'd like to see how you execute your ems based off a distant parent strategy. I can't wrap my head around it.