Fixed element that pushes back content
Asked Answered
L

2

6

I a looking for a way to have a fixed element at the top of the page that would change in height according to the page width and that would also push back the content bellow. I've managed something so far but I'm hoping for a much cleaner solution. What I did is to have 2 top elements with the same content. One is set to position fixed, and the other one to relative, but with no opacity ...

#top-1 { position: fixed; background-color:#fff}
#top-2 {position: relative; opacity:0;}
#content { background-color: #FFF; background-color:#CCC }

I've set up an example here http://jsfiddle.net/q3G7F/6/ Its working exactly how I need it to be, but maybe somebody has a better idea ?
Thanks,

Lemkul answered 9/11, 2012 at 1:56 Comment(0)
D
3

You can do this with a small jQuery (or javascript) snippet.
Change the CSS to this:

#top-1 { position: fixed; top: 0; background-color:#fff}
#content { background-color: #FFF; background-color:#CCC }​

Add this script at the bottom of your page (requires jQuery). This should add a top margin to content and make room for your top element.

<script>
    $(document).ready(function() {
       $('#content').css('margin-top', $('#top-1').height() + 'px');
    }); 
</script>

Here's a working example: http://jsfiddle.net/g6CnA/ .

Update

You'd also need to listen to window resize events and adjust the margin when the top element's height changes.

$(document).ready(function() {
    $('#content').css('margin-top', $('#top-1').height() + 'px');   
}); 

$(window).resize(function() {
    $('#content').css('margin-top', $('#top-1').height() + 'px');        
});           

jsFiddle: http://jsfiddle.net/g6CnA/1

Designed answered 9/11, 2012 at 13:48 Comment(5)
This is working like a charm ! Thank you very much. The website is still in development but you can see the result here www.lucieduval.com/section2/projet-1/Lemkul
Looks great. One thing though, I don't think you need to put this code into a window load event when using document ready. They serve the same purpose. The window load event executes a bit later.Designed
It's #menu, not #top-1 on your page ;)Designed
You are totally right. I copied the source code jsfiddle result frame the window...I should've copied you code...Lemkul
Yeah I figured out... I'm no programmer, rookie mistake ;)Lemkul
G
0

In your CSS, if you set an explicit height (in px or anything NOT %) on the parent element of the #top-1 and the #content, you should be able to set the height of the #top-1 and the margin-top of the #content to the same percentage. That would give you the desired behavior, but this particular method will only work if you can explicitly set the height of their parent.

Grandfatherly answered 9/11, 2012 at 14:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.