You don't need an additional element or Javascript any longer. Use fit-content. For headings, for example:
fit-content
h1 { inline-size: fit-content; /* or `width` in LTR and RTL reading */ margin-inline: auto; }
See a demo on Codepen.