Skip to content

Instantly share code, notes, and snippets.

@ericcornelissen
Last active January 28, 2019 20:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ericcornelissen/e0272b60fba665a9db67065c5c7c3d4d to your computer and use it in GitHub Desktop.
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)
/**
* 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