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

Solution 1:

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/

Solution 2:

The issue stated is, as far as my CSS knowledge will take me, not perfectly solvable with purely CSS.

Mike M. Lin's answer is a very ingenious method, I love the creativity, but there are some errors with it that I can expand on.

NOTE: If anyone finds out the general solution, please let us know, since no-body has done it. Etsy, Amazon, Redbubble, can't see this being achieved anywhere...


1)

You do not need "2 minus the length of the array of div items", this could get computationally expensive for large n of items. Rather, as an approximate rule, you need enough placeholder "blocks" to create a new line in the container. In fact, the number of placeholders is (in pseudocode):

let n = number of block items to display
let n_max = number of block items that fit into one row
let n_ph = number of "placeholder" block items

/*if number of items exceeds max number for a row (starts a new line), then 
 you'll need to start another line with n_max - 1 placeholders*/
if n >= n_max then
    n_ph = n_max - 1
end if

//you don't need any placeholders if number of items fills all rows completely
if n % n_max == 0 then
    n_ph = 0
end if

Notice that I have omitted the case when n < n_max. That is difficult, and you will have to play around with your n_ph values for when n < n_max. If you need n_ph to work for different window sizes, I would consider adding a window width observer and adding or taking away a placeholder for your "responsive" width bands. It is a pain, but you will likely either not have n < n_max ever, or, your n_max is small and it's not a pain to "manually taylor" n_ph for the responsive bands.

2)

You don't need the container to be inline-block. It works with or without it I have found.