Search code examples
containerscentercss

Shrink-wrap and center a container for inline-block elements


I have a bunch of inline-block elements over several lines which I'd like to center horizontally. The inline-block elements all have the same fixed size, but I'd like the centering to be able to handle page resizing and adding or removing elements.

I've stripped down the html/css and removed the attempt at centering for clarity. It's at http://jsfiddle.net/fe25H/1/

If you resize the results window so that the third inline-block element drops down, the container fills the width and we get this:

-----------------BODY------------------
|                                     |
||-------------CONTAINER-------------||
||-INLINEBLOCK---INLINEBLOCK--       ||
|||____________||____________|       ||
||-INLINEBLOCK--                     ||
|||____________|                     ||
||___________________________________||
|_____________________________________|

rather than this:

-----------------BODY------------------
|                                     |
|   |----------CONTAINER---------|    |
|   |-INLINEBLOCK---INLINEBLOCK--|    |
|   ||____________||____________||    |
|   |-INLINEBLOCK--              |    |
|   ||____________|              |    |
|   |____________________________|    |
|_____________________________________|

edit based on ptriek's answer regarding a JavaScript solution:

Ptriek's code was a useful starting point; it works for the specific case, but not the general one. I've mostly rewritten it to be more flexible (see http://jsfiddle.net/fe25H/5/).


Solution

  • After thinking a bit about it, I agree with Wex' comment above.

    So I fiddled a JavaScript solution (jQuery) - I'm not an expert on this, so the code might be improved - but I guess it does exactly what you need:

    var resizeContainer = function () {
        var w_window = $(window).width();
        var w_block = $('.inlineblock').width();
        if (w_window < w_block * 3 && w_window >= w_block * 2) {
            $('.container').width(w_block * 2);
        } else if (w_window < w_block * 2) {
            $('.container').width(w_block);
        }  else {
            $('.container').width(w_block * 3);
        } 
    };
    
    
    $(document).ready(resizeContainer);
    $(window).resize(resizeContainer);
    body {
        text-align:center;
    }
    .container {
        display: inline-block;
        background-color: #aaa;
        text-align:left;
    }
    .inlineblock {
        display: inline-block;
        width: 200px;
        height: 200px;
        background-color: #eee;
    }
    <div class='container'>
        <div class='inlineblock'></div>
        <div class='inlineblock'></div>
        <div class='inlineblock'></div>
    </div>

    http://jsfiddle.net/ptriek/fe25H/4/