Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 344
Tommy Brunn Avatar asked Sep 15 '26 08:09

Tommy Brunn


2 Answers

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

this can help you

like image 142
Senad Meškin Avatar answered Sep 16 '26 22:09

Senad Meškin


(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...

like image 26
DaveRandom Avatar answered Sep 16 '26 21:09

DaveRandom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!