Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

css

flexbox

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

like image 938
Fellow Stranger Avatar asked Sep 09 '15 15:09

Fellow Stranger


Video Answer


1 Answers

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, if you will. align-self on absolutely-positioned boxes applies along the 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>
like image 58
TylerH Avatar answered Oct 07 '22 01:10

TylerH