The toRem
function is a utility for converting length units (px, em, pt) to rem units in JavaScript.
This conversion is particularly useful for responsive web design, where rem units provide scalability and flexibility. The module simplifies the process of ensuring that elements scale proportionally across different screen sizes by leveraging the rem unit, which is based on the root element's font size.
- Features
- Installation
- Usage
- Basic Conversion
- Specifying Decimal Places
- Handling Other Units
- Unrecognized Units
- License
- Technologies
- Multiple Units: Converts px, em, and pt units to rem.
- Customizable Precision: Allows specifying the number of decimal places in the returned value.
- Error Handling: Returns the original value for unrecognized units and logs a warning.
(go to top)
To install the toRem
function, use the following npm command:
- from GitHub (npm/yarn):
npm install --save-dev git+https://github.com/SimplyBuilder/sb-module-to-rem.git
yarn add --dev git+https://github.com/SimplyBuilder/sb-module-to-rem.git
- from npm (npm/yarn):
npm install --save-dev @jamilservices/sb-module-to-rem
yarn add --dev @jamilservices/sb-module-to-rem
Note
This will add the toRem module as a development dependency in your project.
- CDN:
https://unpkg.com/@jamilservices/sb-module-to-rem@latest/src/main.js
https://cdn.jsdelivr.net/gh/SimplyBuilder/sb-module-to-rem@latest/src/main.min.js
(go to top)
Once installed, you can import the toRem function into your JavaScript project like so:
- from install (npm/yarn):
import { toRem } from '@jamilservices/sb-module-to-rem';
- from cdn (html):
<script type="module">
import { toRem } from 'https://unpkg.com/@jamilservices/sb-module-to-rem@latest/src/main.js';
// code
</script>
or
<script type="module">
import { toRem } from 'https://cdn.jsdelivr.net/gh/SimplyBuilder/sb-module-to-rem@latest/src/main.min.js';
// code
</script>
Now you can use the function in your project to convert length units to rem.
(go to top)
Convert a length from pixels to rem:
const lengthInRem = toRem("24px");
console.log(lengthInRem); // Output: "1.5rem"
(go to top)
You can specify the number of decimal places in the returned value:
const preciseLengthInRem = toRem("18px", 2);
console.log(preciseLengthInRem); // Output: "1.12rem"
(go to top)
Convert lengths from em or pt to rem:
const lengthFromEm = toRem("2em");
console.log(lengthFromEm); // Output based on default base of 16px for 1em
const lengthFromPt = toRem("12pt");
console.log(lengthFromPt); // Output based on conversion factor from pt to px to rem
(go to top)
For unrecognized units, the original value is returned:
const unchangedLength = toRem("5vw");
console.log(unchangedLength); // Output: "5vw"
Released under MIT by @jamilservicos. (go to top)
- You can freely modify and reuse.
- The original license must be included with copies of this software.
- Please link back to this repo if you use a significant portion the source code.