Margin Collapsing in CSS

In PSPDFKit for Web 2022.1, we announced support for headers and footers when using the PDF Generation component. This allows you to specify custom DOM containers that will be rendered across each page of a generated PDF.
In this blog post, I’ll explore how — while working on the new headers and footers feature — I identified and solved a particular bug. This bug was related to a surprising behavior with margin collapsing in CSS that affects the position and sizing of elements. For context, I’ll begin by explaining the scenario we were facing, and then, I’ll discuss the approach I took while debugging it and the underlying margin collapsing mechanisms that played into this.
Measuring Headers and Footers
The HTML editor of the view above shows the HTML template, along with the resulting PDF. If you look closely at the elements with pspdfkit-header
and pspdfkit-footer
as their id
attributes, notice how their contents are repeated across each page of the generated PDF.
An essential part of this implementation involves measuring the size and position of the elements defined in the template serving as header or footer.
Let’s take the footer for instance. The footer is supposed to be the very last element present in the HTML template that will generate the PDF form. We can use the Element.getBoundingClientRect()
method on the footer to get its height
and bottom
position, and intuitively it might seem like that bottom
position should also match the end of the whole page. However, it turns out there’s more to it than expected.
Take the following snippet:
<html> <body> <!-- ... --> <div id="pspdfkit-footer"> <p class="footer-columns"> <span>Purchase Order</span> <span>Page {{ pageNumber }} of {{ pageCount }}</span> </p> </div> </body></html>