def page_width_or_height(box, containing_block_size):
    """Take a :class:`OrientedBox` object and set either width, margin-left
    and margin-right; or height, margin-top and margin-bottom.

    "The width and horizontal margins of the page box are then calculated
     exactly as for a non-replaced block element in normal flow. The height
     and vertical margins of the page box are calculated analogously (instead
     of using the block height formulas). In both cases if the values are
     over-constrained, instead of ignoring any margins, the containing block
     is resized to coincide with the margin edges of the page box."

    https://drafts.csswg.org/css-page-3/#page-box-page-rule
    https://www.w3.org/TR/CSS21/visudet.html#blockwidth

    """
    remaining = containing_block_size - box.padding_plus_border
    if box.inner == 'auto':
        if box.margin_a == 'auto':
            box.margin_a = 0
        if box.margin_b == 'auto':
            box.margin_b = 0
        box.inner = remaining - box.margin_a - box.margin_b
    elif box.margin_a == box.margin_b == 'auto':
        box.margin_a = box.margin_b = (remaining - box.inner) / 2
    elif box.margin_a == 'auto':
        box.margin_a = remaining - box.inner - box.margin_b
    elif box.margin_b == 'auto':
        box.margin_b = remaining - box.inner - box.margin_a
    box.restore_box_attributes()
Take a :class:`OrientedBox` object and set either width, margin-left
and margin-right; or height, margin-top and margin-bottom.

"The width and horizontal margins of the page box are then calculated
exactly as for a non-replaced block element in normal flow. The height
and vertical margins of the page box are calculated analogously (instead
of using the block height formulas). In both cases if the values are
over-constrained, instead of ignoring any margins, the containing block
is resized to coincide with the margin edges of the page box."

https://drafts.csswg.org/css-page-3/#page-box-page-rule
https://www.w3.org/TR/CSS21/visudet.html#blockwidth
weasyprint/layout/page.py