Edit: The code bellow is now built-in to TeX4ht sources, you can require it using the Gin-percent option. It may take some time to be included in TeX Live though.
That linked answer is really old and obsolete. You can use \Configure{Gin-dim} command to change the way how image dimensions are calculated now. By default, TeX4ht relies on information about image dimensions provided by the Graphics package. So if you use explicit dimensions (like width=0.5\textwidth), the actual dimension calculated by TeX is used.
One problem is that if you set only one dimension, for example width, the other dimension will be set to the same value. You usually don't want this, unless your image is a square. To get the correct value for all dimensions, Graphics uses a .xbb file for image. It can be created using the following command:
ebb -x *.jpg
Run analogous command for every other supported image format you use. This will ensure that correct values are used for implicitly calculated dimensions.
Now, to your actual question. Thanks to the LaTeX 3 project, we can now use the l3fp package to calculate the image dimensions in percents. It is much easier to use than \dimexpr command, which has lot of limitations.
Try the following .cfg file:
\Preamble{xhtml}
\makeatletter
\ExplSyntaxOn
\Configure{Gin-dim}{style="width:\fp_eval:n{round(\Gin@req@width/\textwidth*100,2)}\char_generate:nn { `\% } { 12 }"}
\ExplSyntaxOff
\makeatother
\begin{document}
\EndPreamble
In this configuration, we divide the image width provided by Graphics by text width. This is then multiplied to get the correct percent value.
For this sample file:
% https://tex.stackexchange.com/q/563276/2891
\documentclass{article}
\usepackage{graphicx}
\begin{document}
\includegraphics[width=0.5\textwidth]{example-image.png}
\end{document}
You get this HTML code:
<p class='noindent'><img style='width:50%' alt='PIC' src='example-image.png' /> </p>
width:60.00061035156249%when I tried it on an example with0.6\textwidth. Rounding to 2 decimal places:round ( \Gin@req@width/\textwidth*100 , 2 )makes this a bit more legible. – Alex Watson Sep 19 '20 at 13:33\Configure{Gin-dim}{style="width:\fp_eval:n{round(\Gin@req@width/\textwidth*100,2)}\%"}. I suggest using\char_generate:nn { `\% } { 12 }instead of\%, because... – frougon Jan 28 '22 at 11:56babel-spanish),\%may have been redefined to include TeX typesetting commands, which web browsers dont appreciate very much (e.g., with\%, one can obtain an HTML attribute likestyle='width:60\protect \unhbox \voidb@x \unskip $\mathsurround (...)') :-). – frougon Jan 28 '22 at 11:57Gin-percentoption. – michal.h21 Oct 23 '22 at 18:56