user2274075
user2274075

Reputation: 117

How to overlay a div upon other div while scrolling using css

I have a webpage header which slides down when a user scrolls down the page.

I am doing this using jquery. It's working but the problem is that the div which holds the header is coming behind the other divs on the page.

I tried to set its postion to absolute or relative but it didnt work for me.

Here is my code.

HTML

 <!--End Toolip-->
    </head>


<div id="headerSlideContainer">

    <div id="headerSlideContent">

        Header content goes here!

    </div>

</div>

<!---Myother divs----->

CSS

<style>
#headerSlideContainer {
    position: fixed;

    top:-50px;
    width: 100%;
    background: black;
}
#headerSlideContent {
    width: 900px;
    height: 50px;
    margin: 0 auto;
    color: white;
}
</style>

JQUERY

<script type="text/javascript">
$(function() {

    var bar = $('#headerSlideContainer');
    var top = bar.css('top');
    $(window).scroll(function() {

        if($(this).scrollTop() > 50) {
            bar.stop().animate({'top' : '5px'}, 500);
        } else {
            bar.stop().animate({'top' : top}, 500);
        }
    });
});
</script>

Upvotes: 0

Views: 1723

Answers (2)

Harshad
Harshad

Reputation: 570

You can set the position of element that you want to keep at top as fixed.

E.g. if you want to keep #headerSlideContainer at top then

#headerSlideContainer{
position: fixed;
}

It will do the trick. No need for jQuery.

Upvotes: 0

Guruprasad J Rao
Guruprasad J Rao

Reputation: 29683

I have tried it and I hope this is what you want..

click this link for demo

What I have added z-index wherever needed.. Now this is how css and html looks.

<div id="headerSlideContainer">

    <div id="headerSlideContent">

        Header content goes here!

    </div>
    <div id="new">
        Other Contents
    </div>

</div>

Css:

#headerSlideContainer {
        position: absolute;
         top:0px;
        width: 100%;

       height:1000px;
        background: black;
    }
    #headerSlideContent {
        width: 900px;
        height: 50px;
        margin: 0 auto;
        color: white;
        background:Red;
        z-index:10000;
        position:fixed;
    }

    #new{
        top:60px;
        z-index:2;
        height:100px;
        background:Orange;
        position:absolute;
        color: white;

    }

Upvotes: 1

Related Questions