CSS position: fixed element and margins

I am trying to create a sticky search so that it is always at the top of the page when scrolling. However, I would like it to take up 100% of the container, not the window.

Here's an example of HTML markup:

<div class="container">
    <div class="searchbox">
        Search Box
    </div>
</div>

      

and CSS:

.container {
    background-color: blue;
    width: 300px;
    padding: 20px;
    height: 40px;
    overflow-x: hidden;
}

.searchbox {
    background-color: red;
    position: fixed;
    width: 100%;
}

      

Here's a script with what's currently going on: http://jsfiddle.net/09ynr879/

I would like it to be indented on the right side by the same amount as it is on the left. Any way to fix this? I would like to be evenly centered with the same margins on the left and right.

Thanks in advance.

Here is a screenshot of the actual site where we had the problem: http://s2.postimg.org/dlj47yqix/Screen_Shot_2014_10_06_at_11_08_24_AM.png

Note that the search engine starts at the right place, but ends at the end of the page, not at the end of the container. We are using Bootstrap 3.2

+3


source to share


3 answers


Items position: fixed

have no siblings. They will always be fixed relative to the page.



If you are not a problem, remove position: fixed;

from .searchbox

and add it to.container

+3


source


This is not possible, the fixed position is out of the stream.

But an alternative solution:



.container {
    background-color: blue;
    width: 300px;
    padding: 20px;
    height: 40px;
    position: fixed;
}

.searchbox {
    background-color: red;
    width: 100%;
}

      

http://jsfiddle.net/09ynr879/4/

+1


source


A fixed position always refers to the entire window. If you only want to do this for the container, you need JavaScript.

I think what you are looking for is:

StickyMojo or jQuery Stickem

Bootstrap has a similar thing called Affix.

0


source







All Articles