1

I'm trying to create a flexbox container that uses flex-wrap: wrap but once it's wrapped is only as wide as it needs to be, that way it can be centered.

Right now, once I resize the window small enough that the elements wrap, the element continues to use up the maximum width it can, thus causing it's child elements to be pushed all the way to the left.

Here's a link to my Plunker

Here's a gif of me resizing the window. As you can see, when the green and red divs have enough space to be on the same line they appear centered, but not when they wrap. Preferably, there should be as much whitespace to the left of the red div as to the right of the green div.

DoesntCenter

Preferably, when the rows wrap it should look like this: isCentered

Any help would be greatly appreciated!

Asons
  • 84,923
  • 12
  • 110
  • 165
Pharylon
  • 9,796
  • 3
  • 35
  • 59
  • 1
    Essentially, as I understand it... **you can't** - That's not the way the line-box model works. https://stackoverflow.com/questions/34995740/css-when-inline-block-elements-line-break-parent-wrapper-does-not-fit-new-width is on point I think. – Paulie_D Jun 22 '17 at 21:29
  • The closest I can get is this, using a media query: https://jsfiddle.net/j1oabjp4/ – Asons Jun 22 '17 at 21:45

1 Answers1

1

You don't want widths on your block elements (the red and green boxes) within the flexbox container. That is similar to a "responsive" design pattern rather than flex.

Flex width (or height) stays the same no matter what. Therefore, be sure to size the container, and flex its children.

.flex-container {
    width: 25%;
    height: auto;
    margin:auto;
    border: 1px solid black;
    display: -webkit-flex; /* Safari */
    display: flex;
}

.flex-container div {
    -webkit-flex: 1;  /* Safari 6.1+ */
    -ms-flex: 1;  /* IE 10 */    
    flex: 1;
}

.green-block{
  /*min-width: 200px;*/
  background-color: green;
  padding: 10px;
  display:flex;
}

.red-block{
  /*min-width: 300px;*/
  background-color: red;
  padding: 10px;
  display:flex;
}
<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
  </head>

  <body>
    <div class="flex-container">
      <div class="flex-row-wrappable">
        <div class="red-block">I'm a red block</div>
        <div class="green-block">Imma green block, and I have more width than my red counterpart.</div>
      </div>
    </div>
  </body>

</html>
ciammarino
  • 154
  • 1
  • 12