Tommy Brunn
Tommy Brunn

Reputation: 2562

Sticky header with variable height

So, I need to have a header that's always displayed at the top of the viewport, even when the user scrolls down. That bit is fairly easy, using something like this:

body {
    padding-top: 100px; /* height of the header */
}

#header {
    position: fixed;
    top: 0;
    left: 50%;
    margin-left: -500px; /* Half the width of the header */
    width: 1000px;
    height: 100px;
}

However, now my problem is that I don't always know how tall the header will be, because the client wants a top banner ad to also follow along, but that might not always be there.

So, sometimes the header might look like this:

<div id="header">
    <img src="#" class="top_banner" />
    <div id="headerbar">
        <h1>Site logo</h1>
    </div>
</div>

And sometimes it might look like this:

<div id="header">
    <div id="headerbar">
        <h1>Site logo</h1>
    </div>
</div>

The good news is that the banner ad will always have the same dimensions. So basically #header could be 100px without the banner, and 250px if the banner is there.

My question to you is: is there a nice CSS ways to solve this? If not, how could I solve it using Javascript?

Upvotes: 3

Views: 2452

Answers (4)

user505157
user505157

Reputation:

I've written a jquery plugin to encounter this kind of problem: https://github.com/ArthurClemens/jquery-sticky-plugin

Check if this works for you.

Upvotes: 0

David Hellsing
David Hellsing

Reputation: 108500

Not sure about CSS, but this javascript should do the basic job for you:

document.body.style.paddingTop = document.getElementById('header').offsetHeight + 'px';

Upvotes: 0

DaveRandom
DaveRandom

Reputation: 88697

(Lazy answer)

Change the className of the #header div depending on whether it has an image or not.

CSS

body {
    padding-top: 100px; /* height of the header */
}

.header_no_image, .header_with_image {
    position: fixed;
    top: 0;
    left: 50%;
    margin-left: -500px; /* Half the width of the header */
    width: 1000px;
}

.header_no_image {
  height: 100px;
}
.header_with_image {
  height: 250px;
}

With image

<div id="header" class="header_with_image">
    <img src="#" class="top_banner" />
    <div id="headerbar">
        <h1>Site logo</h1>
    </div>
</div>

Without image

<div id="header" class="header_no_image">
    <div id="headerbar">
        <h1>Site logo</h1>
    </div>
</div>

There is probably a better solution but this would work...

Upvotes: 1

Senad Meškin
Senad Meškin

Reputation: 13756

$(document).ready(function(){
 $('body').css('padding-top', $('#header').height() + 'px');
});

this can help you

Upvotes: 4

Related Questions