Reputation: 477
I have two div
elements, one of which has position: absolute
. My goal is to position this div at the bottom of its parent by using margin-top: auto
.
This approach to positioning the div
works well without position: absolute
(see snippet)
.profileMain {
display: flex;
}
.userInfo {
width: 50%;
margin-top: auto;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
background: red;
}
.userPrints {
width: 50%;
display: flex;
flex-direction: column;
align-items: center;
background: blue;
margin-bottom: 10em;
}
footer {
height: 10em;
background: gray;
width: 100%;
}
<div class="profileMain">
<div class="userInfo">
<p>This div is bottom positioned</p>
</div>
<div class="userPrints">
<p>This div has normal positioning</p>
</div>
</div>
<footer></footer>
When position: absolute
is added, margin-top: auto
is ignored. (see snippet)
.profileMain {
display: flex;
}
.userInfoHolder{
height: 100%;
width: 50%;
}
.userInfo {
width: 50%;
position: absolute;
margin-top: auto;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
background: red;
}
.userPrints {
width: 50%;
display: flex;
flex-direction: column;
align-items: center;
background: blue;
margin-bottom: 10em;
}
footer {
height: 10em;
background: gray;
width: 100%;
}
<div class="profileMain">
<div class = "userInfoHolder">
<p>This div retains the positioning</p>
</div>
<div class="userInfo">
<p>This div is bottom positioned</p>
</div>
<div class="userPrints">
<p>This div has normal positioning</p>
</div>
</div>
<footer></footer>
Why doesn't this approach work with position: absolute
? Is there an alternative approach I can use to get the result I'm looking for?
Upvotes: 0
Views: 2023
Reputation: 2516
You should understand, when you add position: absolute
the margin-top: auto
property doesn't work. So to make it position to bottom of its parent element, you have to add bottom: 0
property and position: relative
to its parent element. Try update your code like this.
.profileMain {
display: flex;
position: relative;
}
.userInfo {
width: 50%;
position: absolute;
margin-top: auto;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
background: red;
bottom: 0;
}
The answer for 'why?' is, when you apply position:absolute to any element, that element starts floating above all other elements simply like a different layer. As such, the element with position:absolute can't render the margin-top: auto property as it won't find the corresponding edge as of from where it should apply the auto value for margin-top property. I guess, this makes it a bit clear on the 'why?'
Upvotes: 4