sunkerton
sunkerton

Reputation: 125

Align flex children to top

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

Upvotes: 8

Views: 8023

Answers (5)

Shubham Verma
Shubham Verma

Reputation: 9933

I also want the same, and most solutions didn't work for me.

I implemented this way.

.box {
  display: flex;
  align-items: stretch;
  height: 300px;
  gap: 10px
}

.box div{
    border: 1px solid red;
}



<div class="box">
  <div>Hello Stackoverflow</div>
  <div>I am top align</div>
  <div>Three
    <br>has
    <br>extra
    <br>text
  </div>
</div>
  
  

Result:

enter image description here

Upvotes: 0

Panna Das
Panna Das

Reputation: 631

you can try like

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

Upvotes: -2

Vincent1989
Vincent1989

Reputation: 1657

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;
}

Upvotes: 0

ankita patel
ankita patel

Reputation: 4251

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>

Upvotes: 2

Cons7an7ine
Cons7an7ine

Reputation: 738

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

Upvotes: 6

Related Questions