Instantly share code, notes, and snippets.

Embed
What would you like to do?
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