Align flex children to top

Viewed 5899

How do I get flexbox children to line up vertically to the top edge of each row?

HTML:

#container {
  align-items: flex-start;
  align-content: flex-start;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
.child {
  margin: auto;
  border: 1px dotted #CCC;
}
img, h3 {
  width: 160px;
}
<div id="container">
  <div class="child">
    <img src="http://via.placeholder.com/160x160">
    <h3>Title</h3>
  </div>
  <div class="child">
    <img src="http://via.placeholder.com/160x160">
    <h3>The quick brown fox jumps over the lazy dog</h3>
  </div>
  <div class="child">
    <img src="http://via.placeholder.com/160x160">
    <h3>Title</h3>
  </div>
  <div class="child">
    <img src="http://via.placeholder.com/160x160">
    <h3>Title</h3>
  </div>
</div>

Demo: https://codepen.io/anon/pen/GOBzOp

What I see is this but I want it to look like this

4 Answers

change margin:auto of .child to margin: 0px auto.

Give justify-content: space-around; to #container id instead of justify-content: space-between; and remove margin: auto; to .child class.

#container {
  align-items: flex-start;
  align-content: flex-start;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
}
.child { 
  border: 1px dotted #CCC;
}
img, h3 {
  width: 160px;
}
<div id="container">
  <div class="child">
    <img src="http://via.placeholder.com/160x160">
    <h3>Title</h3>
  </div>
  <div class="child">
    <img src="http://via.placeholder.com/160x160">
    <h3>The quick brown fox jumps over the lazy dog</h3>
  </div>
  <div class="child">
    <img src="http://via.placeholder.com/160x160">
    <h3>Title</h3>
  </div>
  <div class="child">
    <img src="http://via.placeholder.com/160x160">
    <h3>Title</h3>
  </div>
</div>

A simple fix would be changing margin: auto; to margin: 0 auto; this will prevent the box auto centralize vertically but retaining its horizontal alignment, like so:

.child {
    border: 1px dotted #CCC;
    margin: 0 auto;
}

you can try like

.child {
    vertical-align: baseline; //either of them
    margin: 0px auto; // any one
}
Related