'Flexbox - center vertically second row
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>
Solution 1:[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>
Solution 2:[2]
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/
Solution 3:[3]
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>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | isherwood |
Solution 2 | Andy Mai |
Solution 3 | isherwood |