def margin_width(box, width, left=True, right=True):
    """Add box paddings, borders and margins to ``width``."""
    percentages = 0
    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
    if left:
        width += box.style['border_left_width']
    if right:
        width += box.style['border_right_width']
    if percentages < 100:
        return width / (1 - percentages / 100.0)
    else:
        return 0
