def margin_width(box, width, left=True, right=True):
    """Add box paddings, borders and margins to ``width``."""
    percentages = 0

    # See https://drafts.csswg.org/css-tables-3/#cell-intrinsic-offsets
    # It is a set of computed values for border-left-width, padding-left,
    # padding-right, and border-right-width (along with zero values for
    # margin-left and margin-right)
    for value in (
        (['margin_left', 'padding_left'] if left else []) +
        (['margin_right', 'padding_right'] if right else [])
    ):
        style_value = box.style[value]
        if style_value != 'auto':
            if style_value.unit == 'px':
                width += style_value.value
            else:
                assert style_value.unit == '%'
                percentages += style_value.value

    collapse = box.style['border_collapse'] == 'collapse'
    if left:
        if collapse and hasattr(box, 'border_left_width'):
            # In collapsed-borders mode: the computed horizontal padding of the
            # cell and, for border values, the used border-width values of the
            # cell (half the winning border-width)
            width += box.border_left_width
        else:
            # In separated-borders mode: the computed horizontal padding and
            # border of the table-cell
            width += box.style['border_left_width']
    if right:
        if collapse and hasattr(box, 'border_right_width'):
            # [...] the used border-width values of the cell
            width += box.border_right_width
        else:
            # [...] the computed border of the table-cell
            width += box.style['border_right_width']

    if percentages < 100:
        return width / (1 - percentages / 100)
    else:
        # Pathological case, ignore
        return 0
Add box paddings, borders and margins to ``width``.
weasyprint/layout/preferred.py