user1810937
user1810937

Reputation: 63

Fixed element that pushes back content

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,

Upvotes: 6

Views: 5700

Answers (2)

user1720624
user1720624

Reputation:

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.

Upvotes: 0

Davorin
Davorin

Reputation: 1204

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

Upvotes: 3

Related Questions