Dangling Cruze
Dangling Cruze

Reputation: 3443

Fix a header on the top relative to a div container

I am having problem fixing the header on top. The header is inside a container div and i want it to stay on the top even if the container div is scrolled.

HTML :

<div class="wrapper">
    <div class="container">
        <div class="fixed">
            SHOULD BE FIXED
        </div>
    </div>
</div>

CSS :

.wrapper{
    width:300px;
    height:200px;
    margin:auto;
    border:1px solid #ddd;
    overflow-y:scroll;
    overflow-x:hidden;
}
.container{
    width:300px;
    position:relative;
    height:1000px;
    background:#111;
}
.fixed{
    background:#aaa;
    position:absolute;
    height:50px;
    width:100%;
    text-align:center;
    font-weight:bold;
    padding:15px 0;
    box-sizing:border-box;
    -moz-box-sizing: border-box;
}

Here is a fiddle.

Upvotes: 4

Views: 1448

Answers (3)

matthummel
matthummel

Reputation: 44

try using jquery for a more crossbrowser friendlier way.

<script>
$(document).ready(function() {
var div = $('**.fixed**');
var start = $(div).offset().top;
$.event.add(window, "scroll", function() {
    var ul = $(window).scrollTop();
    $(div).css('position',((ul)>start) ? 'fixed' : '');
});
});
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') 
    || location.hostname == this.hostname) {

    var target = $(this.hash);
    target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
       if (target.length) {
         $('html,body').animate({
             scrollTop: target.offset().top
        }, 2000);
        return false;
    }
}
});
</script>

Upvotes: -1

Xawier
Xawier

Reputation: 165

Change in .fixed class postion:absolute for postion:fixed and set width to 300px! :)

CSS:

.fixed{
    background:#aaa;
    position:fixed;
    height:50px;
    width:300px;
    text-align:center;
    font-weight:bold;
    padding:15px 0;
    box-sizing:border-box;
    -moz-box-sizing: border-box;
}

http://jsfiddle.net/F2Fhd/4/

Upvotes: 0

VisioN
VisioN

Reputation: 145478

Style position: fixed is the way to go:

.fixed {
    position: fixed;
    width: inherit;
}

DEMO: http://jsfiddle.net/F2Fhd/3/

Upvotes: 3

Related Questions