LESS Mixin for PX to REM Conversion
For the project I was working on, rather than having one base font size, we have two based on a desktop and mobile viewport. | |
@mobile-base-font: 16; | |
@desktop-base-font: 18; | |
html { | |
font-size: (@mobile-base-font*1px); /* rem unit for mobile and tablet */ | |
@media @desktop { | |
font-size: (@desktop-base-font*1px); /* rem unit for laptop and desktop */ | |
} | |
} | |
//calculates REMs from PX for mobile/tablet base fonts (16px) | |
.mobile-font-size(@font-size: @mobile-base-font) { | |
@rem: round(@font-size / @mobile-base-font, 3); //rounds to 3 decimal places | |
//font-size: @font-size * 1px; //fallback to pixels | |
font-size: ~"@{rem}rem"; | |
} | |
//calculates REMs from PX for laptop/desktop base fonts (18px) | |
.desktop-font-size(@font-size: @desktop-base-font) { | |
@rem: round(@font-size / @desktop-base-font, 3); //rounds to 3 decimal places | |
//font-size: @font-size * 1px; //fallback to pixels | |
font-size: ~"@{rem}rem"; | |
} | |
USAGE | |
Place the designated pixel size within the parenthesis and the mixin will convert it to REMs based on the base font size. Use media queries for specific viewports as needed. | |
small { | |
.mobile-font-size(14); | |
@media @desktop { | |
.desktop-font-size(14); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment