← Back toHTML DOM

Measure the width of given text of given font

Written byPhuoc Nguyen
28 Feb, 2020
Last updated
03 Mar, 2020
Level 2 — Intermediate

1. Use the canvas' measureText() method

const measureWidth = function (text, font) {
// Create new `canvas` element
const canvas = document.createElement('canvas');

// Get the context
const context = canvas.getContext('2d');

// Set the font
context.font = font;

// Measure the text
const metrics = context.measureText(text);

// Return the width in pixels
return metrics.width;

2. Use a fake element

const measureWidth = function (text, font) {
// Create an element
const ele = document.createElement('div');

// Set styles
ele.style.position = 'absolute';
ele.style.visibility = 'hidden';
ele.style.whiteSpace = 'nowrap';
ele.style.left = '-9999px';

// Set font and text
ele.style.font = font;
ele.innerText = text;

// Append to the body

// Get the width
const width = window.getComputedStyle(ele).width;

// Remove the element

return width;

See also

If you found this post helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks 😍. Your support would mean a lot to me!

Questions? 🙋

Do you have any questions about front-end development? If so, feel free to create a new issue on GitHub using the button below. I'm happy to help with any topic you'd like to learn more about, even beyond what's covered in this post.
While I have a long list of upcoming topics, I'm always eager to prioritize your questions and ideas for future content. Let's learn and grow together! Sharing knowledge is the best way to elevate ourselves 🥷.
Ask me questions

Recent posts ⚡

Newsletter 🔔

If you're into front-end technologies and you want to see more of the content I'm creating, then you might want to consider subscribing to my newsletter.
By subscribing, you'll be the first to know about new articles, products, and exclusive promotions.
Don't worry, I won't spam you. And if you ever change your mind, you can unsubscribe at any time.
Phước Nguyễn