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
With jQuery, you can use .resize()
, .css()
, and .height()
:
$(window).resize(function() {
$(document.body).css("margin-top", $(".header-fixed").height());
}).resize();
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With