Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

CSS

Aligning a grid of divs using flexbox

I've been working on a small project that's basically a grid of divs; I also wanted them to have equal heights across each row, so I decided to try using flexbox. It started off well, but using space-around or space-between doesn't quite work as the last row can contain a varying quantity of items less than what fills the row (depending on the viewport). I tried switching the justify-content value to flex-start which helped again, but now I'm stumped on adjusting the margins. More or less I just want the child elements centered inside the container while retaining the left-flowing justify. I also considered not using flexbox at all but the equal heights are fairly important so I'd prefer a solution involving it.

It's probably something that I'm just overlooking from scrambling around and applying a new skill, so any help would be appreciated. I created a codepen with what should be the relevant html and css.

http://codepen.io/anon/pen/rxBegL

1 Answer

Jonathan Grieve
MOD
Jonathan Grieve
Treehouse Moderator 91,253 Points

Try adding a margin top and margin left in your flex item context to seperate the boxes when they go multi-line.

.show-content {
  background-color: rgba(241, 241, 241, 1);
  border: 1px solid #eaeaea;
  border-radius: 10px;
  box-shadow: 0 2px 2px rgba(78, 78, 78, 0.3);
  max-width: 380px;  
  flex-direction: column;
  margin-top: 15px;/**/
  margin-left: 20px;
}

.container {
  background-color: gray;
  width: 90%;
  display: flex;
  flex-flow: row wrap;
  justify-content: flex-start;
  /*justify-content: space-between;*/
  /*justify-content: space-around;*/
}

Use justify-content: flex-start to get left alignment. This makes sense because with a column flex direction it works along the horizontal axis of flexbox.

Hope this helps :)

I had tried adjusting the margins as well which looked like helped, but I think my bigger issue is that I'd like the child elements centered inside the container; however, I can't use flexbox's justify-content: center because it would interfere with the last row, nor can I set the child elements to inline-block and then center the container (since I set the children elements to act as flex containers to pin the links to the bottom of each of them.).

(Thanks for the help)