我试图在我的网页上设置一个固定的标题,即它应该始终保持可见,即使在滚动时也是如此。请注意,我的页面是固定宽度 (800px) 并在屏幕上水平居中。
我尝试过的:
<header class="noselect" style="position:fixed; top:0px; height:70px;
background-color:#222D2D; margin:auto;">
<p>
<!-- header stuff goes here -->
</p>
</header>
<div class="separator clearfloat" style="position:fixed; top:71px; height:1px;">
</div>
分隔符是一条水平线,应覆盖整个屏幕宽度,请参见页脚。
问题:
1. 使用 position:fixed
也将其放置在 left=0,而不是居中。
2.分隔符不显示。
我可以通过将分隔符放在页眉中来使分隔符可见,但宽度限制为 800 像素:
<header class="noselect" style="position:fixed; top:0px; height:70px;
background-color:#222D2D; margin:auto;">
<p>
<!-- header stuff goes here -->
</p>
<div class="separator clearfloat"></div>
</header>
测试页是here .
我该如何解决这个问题?
我会将父元素定位为固定的,并在 header
的中心放置 margin: 0 auto;
jsFiddle Demo
HTML:
<div id="top">
<header>Header</header>
</div>
<main>
<!-- Lots of content here. -->
</main>
CSS:
#top {
position: fixed;
left: 0; top: 0px; right: 0;
z-index: 1;
/* The below styling is here for illustrative purpose only. */
border-bottom: 1px solid #c1c1c1;
background: #fff;
opacity: 0.9;
}
#top header,
main {
width: 500px;
margin: 0px auto;
}
#top header {
height: 100px;
/* Border styling is here for illustrative purpose only. */
border-left: 1px dashed #c1c1c1;
border-right: 1px dashed #c1c1c1;
}
main { margin-top: 100px; /* Should be the same as '#top header' height. */ }
我是一名优秀的程序员,十分优秀!