Bodil132 Bodil132 - 4 months ago 39
CSS Question

How do I keep a fixed header on top if there's a small strip on top of it?

thank you so much for taking a look at my question.

I'm trying to Keep a header on top of the page using CSS's fixed positioning. the problem is that I have a small content strip on top of the header and when I scroll down the header stays fixed but the gap where the strip is supposed to be remains:

enter image description here

Here's the code that's handling all of this:

-> HTML:

<!-- Strip -->
<div class="tp-top-bar">
<div class="container">
<div class="row">
<div class="col-md-6 tp-top-add">
<p><i class="fa fa-clock-o" aria-hidden="true"></i> Monday - Friday : 8:00am - 5:00pm</p>
<div class="col-md-6">
<ul class="tp-top-links">
<li><a href="#"><i class="fa fa-facebook" aria-hidden="true"></i></a></li>
<li><a href="#"><i class="fa fa-twitter" aria-hidden="true"></i></a></li>
<li><a href="#"><i class="fa fa-linkedin" aria-hidden="true"></i></a></li>

<div class="header-container">
<div class="tp-header">
<div> ...... </div>

<div class="tp-navbar">

-> CSS:


How would I prevent this gap from happening when scrolled? Do I need some jQuery? Basically I want the header to collapse on top and always remain on top somehow.... Any help on this would be greatly appreciated!


Attach a scroll event handler to the document and watch to see if the document has been scrolled past the height of your thin strip. If it has, that's when you set the position of your header to fixed. In the fiddle below, I'm adding & removing a class to/from the header to accomplish this:

Fiddle w/ solution

EDIT: Updated the solution to account for extra padding/margin needed by the content to not see a "jump" when the header becomes fixed.

$(document).on('scroll', function() {
  if ($(this).scrollTop() >= $('#smallstrip').height()) { 
    $('#content').css('margin-top', $('#fixedheader').height());
  else {
    $('#content').css('margin-top', 0);