Is time from acceptance to publication purely a matter of space issues? While it is clear to me why time from submission to acceptance can vary a lot (given that this involves that most fickle of creature: the reviewer), it is less clear what determines how long it takes for an accepted paper to be published.

Is this purely a matter of all accepted papers being put in a queue and then the journal selects from the top until they fill out each issue (possible going a bit further down to make the page counts fit)?
Or is it common that papers are "pushed" forward in the queue based on various factors (and if so, which factors)?

If it makes a difference, I am mostly interested in math journals, but I am also curious about possible dependency on the field.
I'd say your second option, various factors impact the progression of an accepted paper.

Commissioning editors might decide that they commission an edited issue with academics deciding on the selection and groupings of articles, and that will disrupt the 'queue' of all accepted articles you mention.

Otherwise, commissioning editors might notice that some recently-accepted articles fit nicely around a specific theme or share a common characteristic that make publishing them together valuable, regardless of the order they were accepted.

Essentially, publishing is a human process, with the advantages and drawbacks that entails. If publication was only down to space, things might be very different.