How to style a div content after fixed div header with dynamic height

user1162738 picture user1162738 · Jul 2, 2012 · Viewed 8.6k times · Source

following situation:

<body>
 <div style="position:fixed; width:100%">[place holder for header]</div>
 <div style="position:relative;width:100%;margin-top:100px">[content]</div>
</body>

I need the header always visible and at the top, so this one should be with position:fixed. A problem occurs after self adjustments of the header - height. If the header is higher than 100px a part of the content is hidden.

How can I (CSS) dynamically set the start position of the content div regarding the end of the header.

Answer

insertusernamehere picture insertusernamehere · Jul 3, 2012

I'm still looking for a CSS only solution, but for the moment here's an idea using just one line of JavaScript – when using jQuery:

JavaScript

$(document).ready(function () {
    $('#content').css('marginTop', $('#header').outerHeight(true) );
});

HTML

<body>
    <div id="header" style="[…]">[place holder for header]</div>
    <div id="content" style="[…]">[content]</div>
</body>

The advantage of using .outerHeight(true) is, that it takes care of borders and margins you may have applied to your header.