Fixed element that pushes back content

非 Y 不嫁゛ 提交于 2019-12-07 04:39:15

问题


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,


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/13301034/fixed-element-that-pushes-back-content

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!