Languages
[Edit]
EN

JavaScript - measure text width

3 points
Created by:
Lilly-Grace-Greig
571

In this article, we would like to show you how to measure text width using JavaScript.

Quick solution:

 

Solution explaination

Edit

Canvas context object provides simple API to measure font metrics. It is necessary just to set specific font-family, font-size, font-weight and use measureText() method that returns metrics for indicated text (metrics like e.g. width).

Reusable function

Edit

In this section, you can find simple tool that helps to measure text width using canvas object.

 

Hack solution

Edit

In this section, you can find solution that mounts invisible element with some text to measure text width. This solution is hack, but it works.

Note: this approach requires <body> element to be mount.

 

See also

Edit
  1. CSS - fit div width to content size

References

Edit
  1. HTMLCanvasElement.getContext() - Web APIs | MDN
  2. CanvasRenderingContext2D.measureText() - Web APIs | MDN

Alternative titles

  1. JavaScript - calculate text width
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join