2

I want to use flexbox to position div children inside a div container.

I want them centered inside the container so I use justify-content: center; and align-items: center;. I also want the children to wrap if there are too many to display side by side, so I use flex-wrap: wrap; and align-content: center;. Everything works as expected as long as all content can be fit inside the container.

If the window is really small however the content is overflowing the container and it does show scrollbars, but the first child is still outside the scroll area. This does not happen when align-content is anything other than center.

It happens in safari, chrome and firefox so I assume it is not a bug.

Any idea what causes this and how to fix it?

I also made a codepen to illustrate this (make the browser window as small as possible and scroll to the top to see the first child clipped from view): http://codepen.io/SubHero/pen/bpZXzm

HTML:

<div class="parent">
    <div class="child">Child1</div>
    <div class="child">Child2</div>
    <div class="child">Child3</div>  
    <div class="child">Child4</div>  
</div>

CSS:

* {
  margin: 0;
  padding: 0;
}

html, body {
  width: 100%;
  height: 100%;
}

body {
  display: flex;
}

.parent {
  display: flex;
  flex-grow: 1;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
  align-content: center;
}

.child {
  width: 300px;
  height: 200px;
  margin: 20px;  
  background-color: #4caf50;  
}
SubHero
  • 119
  • 7
  • 1
    Thanks for pointing this out. Auto margins did indeed solve it, although couldn't add it to the children as I had many (the referenced problem had only 1 child). Adding an extra div in combination with auto margins solved it! Thank you!! – SubHero May 12 '16 at 21:16

1 Answers1

-1

Removing

align-content: center;

fixes the problem.

When the align-content property is set to center, it places flex items in such a way that their centers are all at the same place vertically. However, when the window is small, the flexbox wraps all elements underneath each other, which means the flex items are centered vertically, and the first child at the top falls out of view. The reason the child at the bottom doesn't do so, is because webpages automatically extend vertically to accomodate the extra height.

Pandaqi
  • 124
  • 1
  • 8
  • When removing the align-content: center the overflow problem is indeed fixed, but the content is then not vertically centered when there is space enough. So that is not an option. – SubHero May 12 '16 at 21:08