Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fixed element that pushes back content

Tags:

css

fixed

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,

like image 457
user1810937 Avatar asked Nov 09 '12 01:11

user1810937


1 Answers

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

like image 133
Davorin Avatar answered Oct 13 '22 12:10

Davorin