GeorgeButter
GeorgeButter

Reputation: 2591

Offset content top margin based on height of fixed header

I have a header which is fixed. Therefore it has been taken out of the flow of the HTML and the content now sits at the top of the page underneath the header. I can't just give #main-content a margin-top because I don't know the height of the header because it varies depending on screen size. How can I make the margin-top responsive to the height of the header?

<div class="header-fixed">
<h1>Logo</h1>
<nav>Home about contact</nav>
</div>
<div class="main-content">
<p>The content at the top is underneath the header
</p>
</div>

Please see my JSfiddle

Upvotes: 5

Views: 8233

Answers (3)

GeorgeButter
GeorgeButter

Reputation: 2591

Thanks for your help I got it working using:

<script>
$( document ).ready(function() {
$(window).resize(function() {
    $('#main-content').css("margin-top", $(".header-fixed").height());
}).resize();
});
</script>

Upvotes: 0

madalinivascu
madalinivascu

Reputation: 32354

Use the resize event

$(window).resize(function(){
var height = $('.header-fixed').height();//take the header height
$('.main-content').css({'margin-top':height});//alter the margin of the wrapped content
}).trigger('resize');//trigger the margin resize when page is loaded

Upvotes: 1

castletheperson
castletheperson

Reputation: 33466

With jQuery, you can use .resize(), .css(), and .height():

$(window).resize(function() {
    $(document.body).css("margin-top", $(".header-fixed").height());
}).resize();

Upvotes: 7

Related Questions