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

2

6

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.

Novice answered 1/7, 2012 at 22:34 Comment(5)
Take care of the syntax : 'width' and not 'widht'Thermostatics
Do you need a pure CSS solution, or can you use JavaScript too? I'm afraid there's no pure CSS solution for this.Baggott
I prefer css but if there is no solution I''ll be happy of the javascript answer.Novice
I just spent some time looking into this, and I'm pretty sure it's impossible without JS.Poultryman
As long as you remove any onload scripts, html ids and all similar dynamic stuff in the 2nd block, ingenious answer from @Etienne is a css-only solution for this problem.Boogie
D
8

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.

Dhole answered 2/7, 2012 at 22:27 Comment(1)
this actually works fine too. I don't think there is a CSS-only solutionNovice
L
6

CSS only solution (although not super clean) could be to display the same block twice: 1st block "position: fixed", 2nd block "visibility: hidden". Since both would have the same height, the role for the 2nd block would be to push down the page content to the appropriate level.

Lui answered 17/1, 2014 at 21:55 Comment(1)
It works perfectly! This could be the only CSS-only solution.Boogie

© 2022 - 2024 — McMap. All rights reserved.