[英]Sticky header with variable height
因此,即使用户向下滚动,我也需要始终在视口顶部显示标题。 使用这样的东西,这一点相当容易:
body {
padding-top: 100px; /* height of the header */
}
#header {
position: fixed;
top: 0;
left: 50%;
margin-left: -500px; /* Half the width of the header */
width: 1000px;
height: 100px;
}
但是,现在我的问题是, 我并不总是知道标题的高度 ,因为客户希望顶部横幅广告也可以跟随,但这可能并不总是存在。
因此,有时标题可能如下所示:
<div id="header">
<img src="#" class="top_banner" />
<div id="headerbar">
<h1>Site logo</h1>
</div>
</div>
有时可能看起来像这样:
<div id="header">
<div id="headerbar">
<h1>Site logo</h1>
</div>
</div>
好消息是横幅广告将始终具有相同的尺寸。 因此,基本上#header可以是没有横幅的100px,如果有横幅则为250px。
我对您的问题是:是否有解决此问题的不错的CSS方法? 如果没有,如何使用Javascript解决呢?
$(document).ready(function(){
$('body').css('padding-top', $('#header').height() + 'px');
});
这可以帮助你
(懒惰的答案)
根据它是否具有图像来更改#header
div的className。
CSS
body {
padding-top: 100px; /* height of the header */
}
.header_no_image, .header_with_image {
position: fixed;
top: 0;
left: 50%;
margin-left: -500px; /* Half the width of the header */
width: 1000px;
}
.header_no_image {
height: 100px;
}
.header_with_image {
height: 250px;
}
带图片
<div id="header" class="header_with_image">
<img src="#" class="top_banner" />
<div id="headerbar">
<h1>Site logo</h1>
</div>
</div>
没有图像
<div id="header" class="header_no_image">
<div id="headerbar">
<h1>Site logo</h1>
</div>
</div>
可能有更好的解决方案,但这将起作用...
不确定CSS,但是此javascript应该可以为您完成基本工作:
document.body.style.paddingTop = document.getElementById('header').offsetHeight + 'px';
我写了一个jQuery插件来遇到这种问题: https : //github.com/ArthurClemens/jquery-sticky-plugin
检查是否适合您。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.