0

I'd like to position second row in the center of container, but I can't figure out how to make it. align-self works in horizontal direction only - even if flex-direction is set to "column".

.first, .second {
  height: 50px;
  width: 100%;
}

.first {
  background-color: wheat;
}

.second {
  align-self: center;
  background-color: purple;
}

.container {
  background-color: silver;
  height: 300px;
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
}
<div class="container">
  <div class="first">
    first
  </div>
  <div class="second">
    second
  </div>
</div>
isherwood
  • 58,414
  • 16
  • 114
  • 157
chudy91
  • 408
  • 3
  • 18
  • First try with the `margin: auto 0` but it also takes into account the first one. – VXp Sep 20 '18 at 20:56
  • I think all what you need is here : https://stackoverflow.com/questions/32551291/in-css-flexbox-why-are-there-no-justify-items-and-justify-self-properties/33856609#33856609 – Temani Afif Sep 20 '18 at 20:59
  • Or just remove `flex-direction: column` & `align-self: center`, same result. – VXp Sep 20 '18 at 21:06

3 Answers3

0

It's difficult to see what is actually happening because the width of .first and .second are set to 100%. If you make them 50x50 squares you can see that align-self works on the cross-axis of the parent container so in this case it makes .second horizontally centered.

A solution that could work is to nest another flexbox within .second like so: https://jsfiddle.net/Lygdk4xo/

Andy Mai
  • 84
  • 5
0

If you do not mind add a third blank div. You can center the second div by setting justify-content to space-between.

.first,
.second,
.third {
  height: 50px;
  width: 100%;
}

.container {
  background-color: silver;
  height: 300px;
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  justify-content: space-between;
}

.second {
  align-self: center;
  background-color: purple;
}
<div class="container">
  <div class="first">
    first
  </div>

  <div class="second">
    second
  </div>

  <div class="third">
  </div>
</div>
isherwood
  • 58,414
  • 16
  • 114
  • 157
Xin Zhou
  • 1
  • 2
-1

Normally you could set the vertical margins of the element with the class of .second to auto to center it but, the element with the class of .first pushes the centered element down just off center. You can fix this by setting a transform: translateY(-50%) on the centered element.

.first,
.second {
  height: 50px;
  width: 100%;
}

.first {
  background-color: wheat;
}

.second {
  align-self: center;
  background-color: purple;
  margin: auto 0;
  transform: translateY(-50%);
}

.container {
  background-color: silver;
  height: 300px;
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
}
<div class="container">
  <div class="first">
    first
  </div>
  <div class="second">
    second
  </div>
</div>
isherwood
  • 58,414
  • 16
  • 114
  • 157
Danny
  • 1,083
  • 2
  • 8
  • 12