Tavi
Tavi

Reputation: 103

how to make a sticky div be on top of other content

i have a little css problem. i've got a div whit an input in it that will stick to the top of the page when page is scrolled down. it works great except images from the page get over it and it looks awfull. i need to make it "on top" of the other content if i can. or at least have an overflow of some sort that will push the scroll just from it, if that makes any sense.

i have to say my css skills are below avarage. here's what ive got so far

HTML:

<div class="searchbox" id="sticky" style="width:60%; padding-left:20%; background-color:white; padding-top:5px; margin-bottom:25px; padding-right:20%; height:35px;">
<form method="get">
<input style="width:80%;" name="title" placeholder="Search..." type="search">
</form>
</div>

the searchbox is not initially on the top of the page so to make it stick when it gets there i have this javascript that adds / removes position fixed

Javascript:

<script>
var header = document.querySelector('.searchbox');
var origOffsetY = header.offsetTop;

function onScroll(e) {
  window.scrollY >= origOffsetY ? header.classList.add('sticky') :
                                  header.classList.remove('sticky');
}

document.addEventListener('scroll', onScroll);
</script>

CSS:

<style>
.sticky {
  position: fixed;
  top: 0;
}
</style>

Upvotes: 1

Views: 1632

Answers (1)

Rainer Plumer
Rainer Plumer

Reputation: 3753

If somethign else jumps on top of your content, use css z-index to order things according to how you would like. _ quick edit for potential future visitors_ hover slides to bring the slide under the mouse on top of others.

fiddle: Fiddle demo Html

<div id="slides">
    <div id="obj1">obj 1</div>
    <div id="obj2">obj 2</div>
    <div id="obj3">obj 3</div>
</div>

Css:

#slides {
    position: relative
    font-size: 20px;
}
#slides > div {
    border: 1px solid gray;
    min-height: 3em;
    position: absolute;
    top: 1em;
    background: green;
    cursor: pointer;
    text-align: center;
    min-width: 4em;
}
#slides > div#obj2 { 
    top: 2em;
    background: red;
    left: 2em;
}
#slides > div#obj3 { 
    top: 3em;
    background: blue;
    left: 4em;
}

JavaScript:

$("#slides > div").mouseover(function(evt) {
    $("#slides > div").css("z-index", "inherit");
    $(evt.target).css("z-index", 4);
});

Upvotes: 3

Related Questions