Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
LESS CSS mixins for margin and padding in rem units with pixel fallback
// This assumes that the font-size on your <html> is 100% (1rem = 16px)
@font-size: 16;
// Margin mixin - enter pixel values in order: margin-top, margin-right, margin-bottom, margin-left
// Usage: .mar(10, 30, 15, 20);
.mar(@mt: 0; @mr: 0; @mb: 0; @ml: 0;) {
@mtv: @mt / @font-size;
@mrv: @mr / @font-size;
@mbv: @mb / @font-size;
@mlv: @ml / @font-size;
margin: ~"@{mt}px" ~"@{mr}px" ~"@{mb}px" ~"@{ml}px";
margin: ~"@{mtv}rem" ~"@{mrv}rem" ~"@{mbv}rem" ~"@{mlv}rem";
// Padding mixin - enter pixel values in order: padding-top, padding-right, padding-bottom, padding-left
// Usage: .pad(5, 10, 5, 10);
.pad(@pt: 0; @pr: 0; @pb: 0; @pl: 0;) {
@ptv: @pt / @font-size;
@prv: @pr / @font-size;
@pbv: @pb / @font-size;
@plv: @pl / @font-size;
padding: ~"@{pt}px" ~"@{pr}px" ~"@{pb}px" ~"@{pl}px";
padding: ~"@{ptv}rem" ~"@{prv}rem" ~"@{pbv}rem" ~"@{plv}rem";

This comment has been minimized.

Copy link

@LaurenceRLewis LaurenceRLewis commented Oct 8, 2015


How would you use 'auto' margin using this mixin?

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