Skip to content

Instantly share code, notes, and snippets.

@matthewwithanm
Last active December 22, 2015 12:08
Show Gist options
  • Save matthewwithanm/6469822 to your computer and use it in GitHub Desktop.
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.
//
// 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';
});
}())`;
}
@aebsr
Copy link

aebsr commented Sep 6, 2013

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.

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