Skip to content Skip to sidebar Skip to footer

Adding Elements After Fixed Header

I have a fixed header at the top of the screen, and if I try to put an element after the header, said element ends up ignoring the height of the header. HTML

Solution 1:

http://jsfiddle.net/09qL0nzv/3/

var p = document.getElementsByTagName("p")[0],
    header = document.getElementsByTagName("header")[0],
    h = window.getComputedStyle(header).getPropertyValue("height");

p.style.marginTop=h;

This will set a margin-top to the paragraph equal to the height of fixed header. However, this does not take padding or border into account. There are two possible solutions for this.

Use box-sizing: border-box on the header. This will make sure that the height, including padding and a border, will be the height as defined in the stylesheet. (I highly recommend using border-box on all your elements, like so: *, *:before, *:after {-moz-box-sizing:border-box;box-sizing: border-box;}.)

Another solution is adding the padding and border to the computed value in JavaScript, and include that value in the margin top that you set to p. I don't like this solution, but it works.

Solution 2:

When you fix the header, any other element you place disregards its very existence.

Only workaround I've seen is to give a padding (or margin). But, from what I understood you need a more dynamic soln. In which case your best solution would be to use client-side scripting say jquery/js to determine elements present height and then add the same as padding for elements below.

Solution 3:

It's the position:fixed that causes the problem here. The header is no longer part of the flow content, so the flow content begins at the top of the page.

There is no ideal solution for this, but an option that might be a little better than changing the <p> margin is to add an empty <div> to the beginning of your content that matches the height of the <header>.

Here's an example JSFiddle:

Solution 4:

For a more dynamic solution, this is what I came up with

$('p').css('margin-top', $('header').outerHeight());
$(window).resize(function() {
  $('p').css('margin-top', $('header').outerHeight());
});

There might be a better way of doing this, but my reasoning was setting the initial margin of the p tag to be the outer height of the entire header, and then whenever the header might change (in this case, that would be when the window is resized), the margin is then re-evaluated on the p tag.

Post a Comment for "Adding Elements After Fixed Header"