Search code examples
htmlcssflexboxalignment

Display first 2 flex items centered to each other and top aligned


I am trying to center align the first 2 blocks to each other (the blocks with a purple border) and have all 3 boxes top aligned. I have achieved this using display: inline-flex, but would it be possible to have the same results using just display: flex?

Fiddle

.container {
  font-size: 0;
  box-sizing: border-box;
}

.blocks {
  display: inline-flex;
}

.blocks-left {
  align-items: center;
  width: 66%;
  vertical-align: top;
  border: 2px solid purple;
}

.blocks-right {
  width: 33%;
}

.block {
  width: 100%;
}

#block-1 {
  background: red;
  height: 100px;
}

#block-2 {
  background: blue;
  height: 200px;
}

#block-3 {
  background: green;
  height: 400px;
}
<div class="container">
  <div class="blocks blocks-left">
    <div id="block-1" class="block"></div>
    <div id="block-2" class="block"></div>
  </div>
  <div class="blocks blocks-right">
   <div id="block-3" class="block"></div>
   </div>
</div> 


Solution

  • If you want to change blocks to block-level display: flex, you can get the same result if you make your container a flexbox and add align-self: flex-start to the blocks-left element - see demo below:

    .container {
      font-size: 0;
      box-sizing: border-box;
      display: flex; /* added */
    }
    
    .blocks {
      display: flex; /* now flex instead of inline-flex */
    }
    
    .blocks-left {
      align-items: center;
      align-self: flex-start; /* added */
      width: 66%;
      vertical-align: top;
      border: 2px solid purple;
    }
    
    .blocks-right {
      width: 33%;
    }
    
    .block {
      width: 100%;
    }
    
    #block-1 {
      background: red;
      height: 100px;
    }
    
    #block-2 {
      background: blue;
      height: 200px;
    }
    
    #block-3 {
      background: green;
      height: 400px;
    }
    <div class="container">
      <div class="blocks blocks-left">
        <div id="block-1" class="block"></div>
        <div id="block-2" class="block"></div>
      </div>
      <div class="blocks blocks-right">
       <div id="block-3" class="block"></div>
       </div>
    </div>