Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS position:fixed element and margins

Tags:

html

css

I'm trying to create a sticky searchbox so that it's always at the top of the page when you scroll. However, I'd like it to take up 100% of the container, not the window.

Here's an HTML markup example:

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

and the 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 fiddle with what's currently happening: http://jsfiddle.net/09ynr879/

I'd like it to be indented on the right side by the same amount it already is on the left. Any way to fix this? I'd like to be evenly in the center with the same margins on the left and on the right.

Thanks in advance.

Here's a screenshot of the actual site where we're having the problem: http://s2.postimg.org/dlj47yqix/Screen_Shot_2014_10_06_at_11_08_24_AM.png

Notice how the searchbox starts at the right place but ends at the end of the page, not at the end of the container. We're using Bootstrap 3.2

like image 426
max1221 Avatar asked Jan 31 '26 15:01

max1221


2 Answers

Elements that are position: fixed have no relative parents. They are always going to be fixed relative to the page.

If it's no problem to you, remove position: fixed; from .searchbox and add it to .container

like image 144
helllomatt Avatar answered Feb 03 '26 05:02

helllomatt


It's not possible, the fixed position get's out of the flow.

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/

like image 38
Filipe Avatar answered Feb 03 '26 05:02

Filipe