Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Automatically align text (using CSS letter-spacing) with JavaScript (example:
* 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 = `${spacing}px`; = `-${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
You can’t perform that action at this time.