Last active
December 22, 2015 12:08
-
-
Save matthewwithanm/6469822 to your computer and use it in GitHub Desktop.
An ugly hack to use rems with pixel fallbacks for any CSS property.
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
// | |
// Usage: | |
// | |
// @import 'remedy.less'; | |
// @remedy-base-size: 16px; | |
// .something { | |
// .remedy('font-size'; 12px); | |
// .remedy('margin'; 1.2rem 3rem); | |
// } | |
// | |
// Two versions of each property will be created: one using rems and one using | |
// pixels. | |
.remedy(@property, @value) { | |
// LESS doesn't have a good way to do this, so we need to do something kinda | |
// like SQL injection: create a value with a terminator (';') followed by | |
// new statements. | |
-remedy-dummy: ~`(function() { | |
return '1; ' | |
// The value for our dummy property | |
+ @{property} + ': ' | |
// The real property. This will be the px version. | |
+ "@{value}" | |
.replace(/[\[\],]/g, '') | |
// Replace any rem lengths with their pixel equivalents. | |
.replace(/\d+(\.\d+)?rem/g, function(v) { | |
return '' | |
+ (parseFloat(v) * parseFloat('@{remedy-base-size}')) | |
+ 'px'; | |
}) | |
+ '; ' | |
// The real property again. This time for the rem version. | |
+ @{property} + ': ' | |
+ "@{value}" | |
.replace(/[\[\],]/g, '') | |
// Replace any pixel lengths with their rem equivalents. | |
.replace(/\d+(\.\d+)?px/g, function(v) { | |
return '' | |
+ (parseFloat(v) / parseFloat('@{remedy-base-size}')) | |
+ 'rem'; | |
}); | |
}())`; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
2 cents, I think remedy.less should include
@remedy-base-size: 16px;
in the less. That way using it doesn't require the var be set, but can be redeclared as needed.