How to line up the top of two centered divs in a flex container?

Viewed 40

Here is an example of my code :

.flex-container {
  height: 300px;
  width: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #ffeeee
}

#item1 {
  width: 100px;
  height: 100px;
  background-color: blue;
}

#item2 {
  width: 120px;
  height: 120px;
  background-color: red;
}
<div class="flex-container">
  <div id="item1"></div>
  <div id="item2"></div>
</div>

https://jsfiddle.net/vL508wax/

I want the blue square to be centered and the top of the red square to be flush with the top of the blue square.

I know I can do this with margin-top for example but I don't think that's a good way to go. Can I do this with flexbox directly ?

2 Answers

A CSS grid solution since it would be difficult with flexbox:

.flex-container{
  height:300px;
  width:300px;
  display:grid;
  grid-auto-flow:column; /* side by side */
  grid-template-rows:100px; /* the blue height here */
  /* center everything*/
  align-content:center;
  justify-content:center;
  /**/
  background: 
    linear-gradient(green 0 0) center/100% 1px no-repeat,
    #ffeeee
}

#item1{
  width:100px;
  height:100%;
  background-color:blue;
}

#item2{
  width:120px;
  height:120px;
  background-color:red;
  transition:1s all;
}
#item2:hover {
  height:160px;
}
<div class="flex-container">
  <div id="item1">
  
  </div>
  <div id="item2">
  
  </div>
</div>

I'm not sure about your use case nor have I done enough testing with this, But if there will always be 2 elements, you can make use of flex wrap alongside align-content: center;

.flex-container {
  height: 300px;
  width: 300px;
  display: flex;
  align-content: center;
  flex-wrap: wrap;
  justify-content: center;
  background-color: #ffeeee
}

#item1 {
  width: 100px;
  height: 100px;
  background-color: blue;
}

#item2 {
  width: 120px;
  height: 160px;
  background-color: red;
}
<div class="flex-container">
  <div id="item1"></div>
  <div id="item2"></div>
</div>

Related