How to set auto-margin boxes in flexible-width design using CSS?

后端 未结 8 1701
一整个雨季
一整个雨季 2020-12-11 02:04

I have DIV with flexible width set e.g. min-width:800px and max-width:1400px. In this DIV, there are many boxes with fix width 200px and display:inline-block. So depending o

8条回答
  •  一向
    一向 (楼主)
    2020-12-11 02:48

    You can float them and just apply a wrapper to the .box which will allow you to margin:auto; the .box relative to the floated wrapper.

    CSS:

    div.wrapper {
        width:100%;
        border:3px solid red;
    }
    div.clear {
        clear:both;
    }
    div.box-wrapper {
        float:left;
        margin:10px 0;
        height:100px;
        width:20%;
    }
    div.box {
        border:1px solid black;
        width:80px;
        height:100px;
        margin:auto;
    }
    

    HTML:

    Demo: http://jsfiddle.net/2avwf/

    I didn't make them 200px wide for the sake of the fiddle window. Just swap that width:80px out with the width you desire.

    If you want to make this a dynamic solution, in which the number of boxes in a row will vary from user to user based off their screen size, etc., simply make 3 or 4 width-defining box-wrapper classes:

    .box-wrapper-25 {
        width:25%;
    }
    .box-wrapper-33 {
        width:33%;
    }
    

    Then with JQuery you can easily detect the width of .wrapper and assign an override class to the box wrappers:

    $('.box-wrapper').each(function(){
        $(this).removeClass().addClass('box-wrapper box-wrapper-25'); // only need 4 per row
    });
    

    Something like this: http://jsfiddle.net/RcDky/

提交回复
热议问题