0

Normally, an element containing wrapping display:inline-block elements takes up 100% of the available width, giving you something like this:

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

Say, instead you wanted to shrinkwrap and center the container:

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

As far as I can tell, this was impossible with traditional CSS and required JavaScript hacks.

Can this problem be solved with flexbox? If so, how?

[Diagrams shamelessly stolen from this question.]

Nathan Arthur
  • 8,287
  • 7
  • 55
  • 80
  • No..flexbox can't do that...no layout method can...that's not the way the line box model works. – Paulie_D Mar 13 '16 at 20:16
  • Probably duplicate - http://stackoverflow.com/questions/34995740/css-when-inline-block-elements-line-break-parent-wrapper-does-not-fit-new-width ...or at least related. – Paulie_D Mar 13 '16 at 20:20
  • @Paulie_D Not directly about flexbox (and also recommends JS); but, yes, related. – Nathan Arthur Mar 13 '16 at 20:45

1 Answers1

0

Use the body as your flex container, and then container becomes a flex item.

Fiddle

HTML:

<body>
  <div class="container">
    <span class="inline-block"></span>
    <span class="inline-block"></span>
    <span class="inline-block"></span>
  </div>
</body>

CSS:

body{
  display:flex;
  justify-content:space-between;
}
.container{
  margin:auto; // centers horizontally
}
.inline-block{
  display:inline-block;
  width:200px;
  height:32px;
  background:#ccc;
}

Feel free to play around with the fiddle. This should give you the basic idea, though.

shamsup
  • 1,952
  • 14
  • 18
  • You can set a max-width on the `.container` element in order to limit the width and have wrapping inside. If there is wrapping and the max-width isn't a multiple of the widths of objects inside, then you'll have whitespace in the right side of the `.container`. To fix this, you can also make the `.container` `display:flex` so that you can control the items inside of it with flexbox as well. – shamsup Mar 13 '16 at 20:19
  • Thanks for giving it a shot, but this doesn't seem to be doing what I'm looking for at all. The container should be only the width of the items inside, and items in the last line should be aligned to the left. Are you able to edit your fiddle with some of your suggestions to get it closer? – Nathan Arthur Mar 13 '16 at 20:50