How to adaptively display text

I’m creating a template where I want the title to adapt to a designated area. If the text is lengthy, it should display in multiple lines using a smaller font size. If the text is brief, it should display in fewer lines using a larger font size.

You can achieve this by measuring the text repeatedly while decreasing the font size until it fits:

#let adaptive-title(body) = context {
  let height = 4cm // box size
  let width = 6cm  // box size
  let size = 50pt  // maximum text size

  while measure(text(size: size, weight: 700, body), width: width).height > height {
    size -= 1pt
  }
  box(
    width: width,
    height: height,
    fill: green, // for visualization only
    text(size: size, weight: 700, body)
  )
}

  • For the document title, you should use the title element. You can use
    #show title: adaptive-title
    
    for that (or simply paste the function definition into the show rule if you only need it in for this)

For one line, there is one-liner – Typst Universe.

However, I would like to display multiple lines when the text is lengthy.