Last active
January 28, 2019 20:25
-
-
Save ericcornelissen/e0272b60fba665a9db67065c5c7c3d4d to your computer and use it in GitHub Desktop.
Automatically align text (using CSS letter-spacing) with JavaScript (example: https://codepen.io/ericornelissen/full/wjNzwR)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Automatically align the text of one element with | |
* the text of another element. | |
* | |
* @param {Node} node The element to align. | |
* @param {Node} target The element to align with. | |
* @license The-Unlicense | |
*/ | |
function alignTextWith(node, target) { | |
const targetWidth = target.offsetWidth; | |
// Get details about the target element | |
const charCount = node.innerHTML.length; | |
const nodeWidth = node.offsetWidth; | |
// Calculate the spacing | |
const widthDiff = targetWidth - nodeWidth; | |
const spacing = widthDiff / (charCount - 1); // x - 1 spaces between characters | |
// Update the target elements styling | |
node.style.letterSpacing = `${spacing}px`; | |
node.style.marginRight = `-${spacing}px`; // counteract spacing after the last character | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment