Skip to main content
3 of 3
Fix snipper a bit and add white-space: nowrap
Red Mercury
  • 4.4k
  • 3
  • 29
  • 33

You can use max-content to measure the pixel width of text.

Here is a utility function that does that. It optionally takes any node as a context to calculate the width in, taking into account any CSS like font-size, letter-spacing, etc.

function measureTextPxWidth( text, template = document.createElement("span") ) { const measurer = template.cloneNode(); measurer.style.setProperty("all", "revert", "important"); measurer.style.setProperty("position", "absolute", "important"); measurer.style.setProperty("visibility", "hidden", "important"); // Prevent wrapping if the text is wider than the screen. measurer.style.setProperty("white-space", "nowrap", "important"); measurer.style.setProperty("width", "max-content", "important"); measurer.innerText = text; document.body.appendChild(measurer); const { width } = measurer.getBoundingClientRect(); document.body.removeChild(measurer); return width; } document.querySelector('.spanTextWidth').innerText = `${measureTextPxWidth('one two three')}px` document.querySelector('.h1TextWidth').innerText = `${measureTextPxWidth('one two three', document.querySelector('h1'))}px`
h1 { letter-spacing: 3px; }
<span>one two three</span> <div class="spanTextWidth"></div> <h1>one two three</h1> <div class="h1TextWidth"></div>

Red Mercury
  • 4.4k
  • 3
  • 29
  • 33