Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Offset content top margin based on height of fixed header

Tags:

html

jquery

css

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

like image 615
GeorgeButter Avatar asked May 18 '16 04:05

GeorgeButter


2 Answers

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

$(window).resize(function() {
    $(document.body).css("margin-top", $(".header-fixed").height());
}).resize();
like image 65
4castle Avatar answered Oct 10 '22 01:10

4castle


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
like image 24
madalinivascu Avatar answered Oct 10 '22 02:10

madalinivascu