Center floated child DIVs in a parent DIV that has fluid width

后端 未结 5 1999
闹比i
闹比i 2021-01-29 06:05

I have the following HTML:

Box1
Box2
5条回答
  •  余生分开走
    2021-01-29 06:30

    Unfortunately you are unable to do this using pure css. If you are willing to use a bit of javascript and jQuery you can easily achieve what you want:

    var parent = $('#parent'),
        container = $('#container'),
        children = container.children('.child'),
        width = children.eq(0).outerWidth() + parseInt(children.eq(0).css('margin-left')) + parseInt(children.eq(0).css('margin-right')),
        maxWidth = children.length * width;
    
    function resizeContainer() {
        var newWidth = Math.floor(parent.width() / width) * width;
        if (newWidth <= maxWidth && newWidth > 0) {
            container.width(newWidth);
        }
    }
    
    $(window).resize(resizeContainer);
    
    resizeContainer();
    

    Example

提交回复
热议问题