Saturday, June 14, 2025

measure-text-in-Typst

measure-text-in-Typst

Adaptive Table Layout in Typst Based on Sentence Length

Goal

We have four sentences and want to arrange them in a table.
The number of columns (1, 2, or 4) should adapt based on how long the sentences are:

  • If the sentences are short → display in 4 columns.
  • If moderately long → display in 2 columns.
  • If very long → stack vertically in 1 column.

This makes the layout responsive and clean, without manual adjustment.

Typst Code

Below is the full Typst code that implements this logic:

#set page(paper: "a4")

// Measure the width of any element
#let widthof(body) = measure(body).width

// Generate four strings: A, B, C, D with n repeated characters
#let get-abcd(n) = ("A"*n, "B"*n, "C"*n, "D"*n)

// Layout and adapt table based on text width
#let show-body(A, B, C, D) = layout(size => {
  let textwidth = size.width
  let maxlen = widthof(A)

  if maxlen < 0.23*textwidth {
    table(columns: (1fr,)*4, A, B, C, D)
  } else if maxlen < 0.46*textwidth {
    table(columns: (1fr,)*2, A, B, C, D)
  } else {
    table(columns: (1fr,), A, B, C, D)
  }
})

// Test cases with different text lengths
#show-body(..get-abcd(10))
#show-body(..get-abcd(20))
#show-body(..get-abcd(30))

Result

As the text length increases, the layout dynamically switches between 4, 2, and 1 column(s). Here’s a visual result of the above code in action:

Typst layout with sentences

This approach is great for building flexible and responsive Typst documents — especially useful when content size is unpredictable.

Popular Posts