Skip to content

Instantly share code, notes, and snippets.

@nireno
Last active December 13, 2023 16:02
Show Gist options
  • Save nireno/7669850dffb41e7bede90b9caa5572ca to your computer and use it in GitHub Desktop.
Save nireno/7669850dffb41e7bede90b9caa5572ca to your computer and use it in GitHub Desktop.
Rem Scaling for TailwindCSS config
/**
* Adapted from [deanmcpherson](https://github.com/tailwindlabs/tailwindcss/discussions/1611#discussioncomment-1959522).
* Scales all rem values for the given theme object.
* @param {Object} theme - The theme object containing the values to be scaled.
* @param {number} from - The original value to scale from.
* @param {number} to - The target value to scale to.
* @returns {Object} - The modified theme object with scaled rem values.
*
* @example
* const defaultTheme = require('tailwindcss/defaultTheme');
* const scaledTheme = scaleRem(defaultTheme, 11, 16);
*
* module.exports = {
* content: ["auto"],
* theme: {
* extend: {
* ...scaledTheme,
* colors: {
* "primary-main": "#F99C2E",
* }
* },
* },
* plugins: [],
* }
*
*
* @example
* const theme = {
* fontSize: '1.5rem',
* padding: ['0.5rem', '1rem', '1.5rem'],
* lineHeight: {
* small: '1.2rem',
* }
* };
*
* const scaledTheme = scaleRem(theme, 16, 14);
* // scaledTheme will be:
* // {
* // fontSize: '1.3125rem',
* // padding: ['0.4375rem', '0.875rem', '1.3125rem'],
* // lineHeight: {
* // small: '1.05rem',
* // }
* // }
*/
function scaleRem(theme, from, to) {
const SCALING_FACTOR = to / from;
const checkValue = (value) => {
if (typeof value === 'string' && value.endsWith('rem')) {
return parseFloat(value) * SCALING_FACTOR + 'rem';
}
return value;
}
const mod = obj => {
if (typeof obj !== 'object') {
return obj;
}
if (Array.isArray(obj)) {
return obj.map(value => mod(checkValue(value)));
}
return Object.keys(obj).reduce((newObj, key) => {
newObj[key] = mod(checkValue(obj[key]));
return newObj;
}, {});
};
return mod(theme);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment