1

I'm trying to create a floating div, which I want to stop at the footer. I've added a margin-top:50px on my floating div, but it surpasses my footer. I need the margin-top to be 50px. How do I fix this?

$(document).ready(function () {

    var length = $('#content').height() - $('#scroll-block').height() + $('#content').offset().top;

    $(window).scroll(function () {

        var scroll = $(this).scrollTop();
        var height = $('#scroll-block').height() + 'px';

        if (scroll < $('#content').offset().top) {

            $('#scroll-block').css({
                'position': 'absolute',
                'top': '0'
            });

        } else if (scroll > length) {

            $('#scroll-block').css({
                'position': 'absolute',
                'bottom': '0',
                'top': 'auto'
            });

        } else {

            $('#scroll-block').css({
                'position': 'fixed',
                'top': '0',
                'height': height
            });

        }
    });

});
#header {
    background: #c2c2c2;
    height: 150px;
}
#wrapper {
    position: relative;
    min-height: 500px; /* Just as an example */
    width: 500px;
}
#content {
    position: absolute;
    background: #d7d7d7;
    width: 150px;
    height: 100%;
}
#right {
    position: relative;
    width: 350px;
    float: right;
    height:200px;
}
#scroll-block {
    background: #0096d7;
    width: 150px;
    color: #fff;
    height:50px;
    margin-top:50px;
}
.clear {
    clear: both;
}
#footer {
    background: #c2c2c2;
    height: 500px; /* Just as an example */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div id="header">Header</div>
<div id="wrapper">
    <div id="content">
        <div id="scroll-block">Sidebar Text here!</div>
    </div>
    <div id="right">This is the text of the main part of the page.</div>
    <div class="clear"></div>
</div>
<div id="footer">Footer</div>

7
  • Why do you "NEED" the margin-top:50px?
    – Wes Foster
    Commented Jan 4, 2017 at 17:23
  • Why do you expect margin-top on your floating div to prevent it from overlapping your footer?
    – TylerH
    Commented Jan 4, 2017 at 17:50
  • @WesFoster I need the margin-top 50px because i have a floating header which is 50px in height. And if I dont add the 50px on the margin-top, the floating div goes under my header.
    – Bel
    Commented Jan 5, 2017 at 8:21
  • @TylerH If you have a better solution, please tell me. Please read what I wrote to WesFoster
    – Bel
    Commented Jan 5, 2017 at 8:23
  • @WesFoster I dont want the div to touch the top also
    – Bel
    Commented Jan 5, 2017 at 15:32

0

Browse other questions tagged or ask your own question.