Search code examples
typst

Place box at the top of the page


I am new to typst and want to style a report using typst. The report should have a blue header with a logo in the right hand corner.

So far I have the following, which creates a box in the header, but the box has a margin to the left and right

#set page(
  header: box(
    width: 100%,
    height: 100%,
    fill: blue
  )[
    #place(right+ horizon)[MYLOGO #h(1cm)]
  ],
  margin: (top: 2.5cm, bottom: 2.5cm, left: 2.5cm, right: 2.5cm)
)


Hello World

img


Solution

  • To build on @David's answer, you can use context to fetch page margins. This way, you don't have to manually match the margin values in the box with the page's values. You can also specify an outset to match the logo's placement with the page's inner right margin, no need for pad:

    #let header-box = context {
      set align(right + horizon)
      let margin = page.margin
      if type(margin) != dictionary {
        // Single value
        margin = (left: margin, right: margin)
      }
      for key in ("left", "right") {
        if margin.at(key, default: auto) == auto {
          panic("No margin value found for `" + key + "`")
        }
      }
      box(width: 100%, height: 100%, outset: (left: margin.left, right: margin.right), fill: blue)[
        MYLOGO
      ]
    }
    
    #set page(
      header: header-box,
      margin: (top: 2.5cm, bottom: 3.5cm, right: 2.5cm, x: 3em)
    )
    
    
    Hello World
    

    enter image description here