Jeff
Jeff

Reputation: 33

Flex items not wrapping

My issue is that I have a section within the article that I made a flexbox, and when I reduce the size of the browser those 3 elements in that flexbox will overlap. Any tips?

body {
  display: flex;
  flex-direction: column;
}
header {
  background: blue;
}
main {
  display: flex;
  flex-direction: row;
  flex: auto;
}
article {
  flex: 2;
  overflow-y: auto;
  background: red;
}
aside {
  flex: 1;
  overflow-y: auto;
  background: green;
}
.test {
  display: flex;
  flex-direction: row;
  flex: auto;
  align-items: stretch;
  background: pink;
}
<body>
  <header>
    Test
  </header>
  <main>
    <article>
      <section>
        test
      </section>
      <section class="test">
        <div>
          div one
        </div>
        div two
        <div>
          div three
        </div>
        <div>
        </div>
      </section>
    </article>
    <aside>
      aside
    </aside>
  </main>
  <footer>
  </footer>
</body>

http://jsfiddle.net/zLmcyjy6/

Upvotes: 2

Views: 3284

Answers (1)

Michael Benjamin
Michael Benjamin

Reputation: 372069

Try adding flex-wrap: wrap to the flex container. Flex items do not wrap by default.


In reference to your website (I didn't use your fiddle demo, which has different code), each of the non-wrapping elements is a <section> child of <section class="other">, which is a row-direction, wrap-enabled flex container.

Each <section> flex item has a flex: 1 applied. This translates to:

  • flex-grow: 1
  • flex-shrink: 1
  • flex-basis: 0

With flex-basis set to zero, the initial main size of the flex item is 0, and the width could shrink to that degree, so there's no opportunity to wrap.

I would suggest changing flex-basis: 0 to something like flex-basis: calc(33% - 2em) (i.e., width minus approx. margin, border, padding), for wider screens. So flex: 1 1 calc(33% - 2em).

And then for smaller screens, using a media query, set flex-basis to something like:

@media screen and ( max-width: 500px ) {
    .fitness, .education, .pastimes {
        flex-basis: 100%;
        display: flex; /* optional; for nicer alignment */
        flex-direction: column;  /* optional; for nicer alignment */ }
    }

Alternatively, if you wanted to avoid using media queries, you could set a fixed value to flex-basis which would enable wrap, as well. Something like flex: 1 0 200px.

Upvotes: 2

Related Questions