Infamous911
Infamous911

Reputation: 1531

CSS - Fixed div as child of a fixed div

In this jsfiddle I want to make it so that the red box always stays aligned with the right edge of the gray "footer" box, regardless of how the width of the "footer" box changes. That is, the red box is in the correct place initially, but when you click the "extend footer" button, the "footer" box gets longer, and the red box doesn't move with it (because I have it as position absolute right now).

How can I make the red box be fixed to the right edge of the gray "footer" box?

Code for jsfiddle:

HTML:

<div class="footerContainer">
    footer
    <div class="aboveFooter"></div>
</div>
<button id="btnClick">
    Extend footer
</button>

CSS:

.footerContainer {
    background-color:#ddd;
    position: fixed;
    padding: 2em;
    left: 0;
    bottom: 0;
}

.aboveFooter {
    position: absolute;
    bottom: 82px;
    left: 52px;
    height: 50px;
    width: 50px;
    background-color:red;
}

JS:

$('#btnClick').on('click',function(){
    $('.footerContainer').html($('.footerContainer').html() + ' longer');
});

Upvotes: 1

Views: 256

Answers (1)

Michael Coker
Michael Coker

Reputation: 53709

You're using left: 52px which will position the red box 52px from the left relative to the positioned parent (.footerContainer). To keep it flush on the right edge, use right: 0;

$('#btnClick').on('click',function(){
    $('.footerContainer').html($('.footerContainer').html() + ' longer');
});
.footerContainer {
    background-color:#ddd;
    position: fixed;
    padding: 2em;
    left: 0;
    bottom: 0;
}

.aboveFooter {
    position: absolute;
    bottom: 82px;
    right: 0;
    height: 50px;
    width: 50px;
    background-color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="footerContainer">
    footer
    <div class="aboveFooter"></div>
</div>
<button id="btnClick">
  Extend footer
</button>

Upvotes: 3

Related Questions