Preserving the appearance of CSS flow while switching position from relative to fixed

I'm wondering what's the best way to deal with this: I have two div in document flow (nav + content), positioned as relative.

In some situations, I will need to give the nav a fixed position. As this removes the nav from the flow, the content div is no longer properly located below. I could add the content some top-margin to compensate, but this would have to be computed because the nav doesn't have a set height (in my example, it's 50% of the window height).

Any suggestion?

JSFiddle: http://jsfiddle.net/6gkVS/

Upvotes: 2

Views: 61

Answers (1)

sheriffderek
sheriffderek

Reputation: 9043

The best way to calculate a number and apply somewhere else, is javaScript, because you have to find that number after the DOM is loaded.

I'm going to just say that as of (this date) you shouldn't be using fixed positioning at all without testing for touch with modernizr, and only in the case that it's "no-touch" use fixed, due to the less that adequate browser support on mobile and touch enabled desktop. Try one out at a store and you'll see what I mean. Jumpy weird fixed headers everywhere.

The fact that your divs are relative doesn't really matter.

The best thing to do, is run modernizr. It will spit out a no-touch class on your html that you can use to style with.

.no-touch nav {
    position: fixed;
    top: 0; left: 0;
}

Then with jQuery, you can do something along these lines - if you are using box-sizing: border-box (which I suggest) than you'll want to use '.outerHeight()' to be sure to include padding and borders. You'll also only want a fixed header when the screen is big enough to accommodate it.

var windowHeight = $(window).height();
var navHeight = $('nav').outerHeight();

if ( windowHeight > 600 ) {
   $('nav').addClass('fixed-nav');
   $('section').css('margin-top', navHeight); 
}

Here is a fiddle. I hope that helps. Sorry there is no way to do it with CSS yet. That would be cool.

Upvotes: 1

Related Questions