When it comes to flexbox alignment and distributing free space within a container, using margin-top: auto
may not be effective due to the lack of a counterweight on the opposite side.
To center the box and align the text at the bottom, one approach is to create a duplicate of the text element and position it on the other side of the box to establish a counterweight.
By achieving balanced distribution on both ends through this method, flex alignment properties such as auto
margins can then function properly.
In fact, even utilizing justify-content: space-between
would be a suitable option in this scenario.
Remember to set visibility: hidden
for the duplicate element.
.container {
background: lightblue;
width: 300px;
height: 300px;
display: flex;
justify-content: center;
flex-direction: column;
align-items: center;
padding: 10px;
}
.box {
background: goldenrod;
height: 30px;
width: 30px;
margin: auto 0; /* Alternatively, use justify-content: space-between on .container */
}
span:first-child {
visibility: hidden;
}
<div class="container">
<span>Text</span>
<div class="box"></div>
<span>Text</span>
</div>
Alternatively, utilize a pseudo-element instead of a duplicate element.
A more subtle and semantic approach involves using a pseudo-element as a duplicate. However, precise knowledge of the actual element's height is required for this technique to succeed.
Here is an example to achieve equilibrium:
.container::before {
content: "";
height: 15px; /* Height must match the actual element's height */
}
.container {
background: lightblue;
width: 300px;
height: 300px;
display: flex;
justify-content: space-between;
flex-direction: column;
align-items: center;
padding: 10px;
}
.box {
background: goldenrod;
height: 30px;
width: 30px;
}
span {
height: 15px;
}
.container::before {
content: "";
height: 15px;
}
<div class="container">
<div class="box"></div>
<span>Text</span>
</div>