Search code examples
cssflexbox

Using flexbox to align one element to the top left and one to the center on a page


When I try to put one element in the top left and one in the center, the top element doesn't go all the way to the left. How do I accomplish this?

.Aligner {
  background-color: blue;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 200px;
}

.Aligner-item {
  max-width: 50%;
  background-color: green;
}

.Aligner-item--top {
  align-self: flex-start;
}
<div class="Aligner">
    <div class="Aligner-item Aligner-item--top">…</div>
    <div class="Aligner-item">…</div>
    <div class="Aligner-item Aligner-item--bottom">…</div>
</div>

http://codepen.io/anon/pen/EVjzzo


Solution

  • From MDN:

    flex-start

    The cross-start margin edge of the flex item is flushed with the cross-start edge of the line.

    This means align-self: flex-start; will align the top edge of your top box with the top edge of the flex box (the beginning of the cross axis).

    The left/right values are along the main axis. You can read more about it in the W3C spec: https://drafts.csswg.org/css-align/#align-self-property

    One way to accomplish your desired layout is to use position properties.

    Note that the addition of position will change the flex behavior; it's sort of an "override" property. align-self on absolutely-positioned boxes applies along the containing block's block axis (in this case, the y-axis).

    You can see more info about absolutely-positioned flex items here: http://www.w3.org/TR/css3-flexbox/#abspos-items

    .Aligner {
      background-color: blue;
      display: flex;
      align-items: center;
      justify-content: center;
      height: 200px;
      position: relative; /* new */
    }
    
    .Aligner-item {
      max-width: 50%;
      background-color: green;
    }
    
    .Aligner-item--top {
      align-self: flex-start;
      left: 0; /* new */
      top: 0; /* new */
      position: absolute; /* new */
    }
    <div class="Aligner">
      <div class="Aligner-item Aligner-item--top">…</div>
      <div class="Aligner-item">…</div>
      <div class="Aligner-item Aligner-item--bottom">…</div>
    </div>