2

In an Elmish app (using Fable and Feliz), I'm trying to create a container (a div) with the exact width as an arbitrary string. Is there a way to measure the width of a string ahead of time (before displaying it)?

redcurry
  • 2,381
  • 2
  • 24
  • 38
  • 2
    Given than Fable just translates F# to JS, it should help to use JS answer: https://stackoverflow.com/questions/118241/calculate-text-width-with-javascript – JL0PD Sep 17 '22 at 06:52
  • 2
    This should do the trick: https://fable.io/repl/#?code=LYewJgrgNgpgBAIQIYGcCWBjAwkgdgN1QCgiQAHGXRAJxAHcUZqA6AFQE8KVSKqFaGTErAAucNLjQiAFAEo4AXiJwVcUXAx5CKRXDAgMEYJRHMAjhCbsAyjFgYRIatIBEzfGhh0X8gFwB+AD44AAlWAFkAGRwCVABRWGNcEWVVdQcAD11NWJRmAHMYESwQZJgMkQB9ACYwOVSVTOYAM1KxAB4AWjgXACMQKDA4aoAGMiykajQkKBcGjREMlrQoKFZysWkm41QIahh1itczOhgfZjo0MBEACzYQaxEp3Hy5ABo4AEYRkY-vkdkJAkUnqQA&html=DwCwLgtgNgfAUHUBTAhgE3gAm54ElgqbhgAOAtEgI4CuAlgG4C8ARAMID2AdmEj+QBUAnqSQtMAY268erXgA8wAenDQA3BJAoATgGcCTGmABm5ABwt4wFagwJgAIw5ohWHMAkouDFLslRfXVYGOiQAd3EwujQwEFYAFgAGRPEQJDoAc3AE5MtrT29fKyUnF3hEFUhYOCA&css=Q – JL0PD Sep 17 '22 at 07:11
  • Can you use CSS [`width: fit-content;`](https://developer.mozilla.org/en-US/docs/Web/CSS/fit-content)? – Brian Berns Sep 17 '22 at 15:38
  • @BrianBerns The problem with that is that I believe I need to show the contents of what is being fit. I don't want to show the actual string (at least not at first). – redcurry Sep 17 '22 at 18:15
  • @JL0PD Thank you, that did the trick. However, I wish I didn't have to set the font manually but instead detect it automatically based on the containing element. – redcurry Sep 17 '22 at 20:03
  • 1
    @redcurry, linked answer contains example of text size for specific element. Author called that method `getCanvasFont` – JL0PD Sep 18 '22 at 02:28

0 Answers0