Search code examples
cssflexbox

Position an item vertically to the top in its parent container


Following a guide on flex items, I have understood is as you can use "align-self" on a item to set its specific position inside its flex container. So in my case of trying to get the item to stay at the top of its container, I have used

align-self: flex-start;

However when I use this option it applies horizontally and not vertically. I have set my flex container to use:

flex-direction: column;

To have the other items centered, I have set the flex container to use:

justify-content: center;

Overall my code looks like this:

.parent {
  display: flex;
  flex-direction: column;
  justify-content: center;
  min-height: 600px;
  background-color: red;
}

.top-container {
   align-self: flex-start;
  background-color: blue;
}

.center-container {
  background-color: green;
  
}

I have tried this in a clean environment, so there is not any extra css or something that are overriding. All the code I'm using is what I have showed here. Any help would be appreciated.


Solution

  • Use .center-container { margin: auto 0; }:

    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    
    .parent {
      display: flex;
      flex-direction: column;
      min-height: 100vh;
      border: dashed 2px red;
      padding: 12px;
      gap: 12px;
    }
    
    .top-container {
      padding: 12px;
      border: dashed 2px blue;
    }
    
    .center-container {
      padding: 12px;
      border: dashed 2px green;
      margin: auto 0;
    }
    <div class="parent">
      <div class="top-container">top-container</div>
      <div class="center-container">center-container</div>
    </div>