中心标题元素,位置固定在页面顶部

时间:2013-04-27 11:40:28

标签: html css position

我有一个特定于Google Chrome的CSS问题。我做了一些研究,但没有人知道如何在没有Javascript的情况下修复它,我不想使用它,因为我的元素将来会改变。

代码在下面,如果您使用它,您将看到子div到达页面的右侧,如果我向父母添加相同的顶部位置值,它将向相反方向移动。

该网站将有更多内容,我想要一个居中的标题,当您滚动页面时,侧边栏和浮动内容将消失在后面。

    <body>
    <!--this should not need any css coding till later on after the site is complete-->
    <center>
        <div class="header_p1">
            <img class="header_p1_child" src="header.png"/>
        </div>
    </center>

和css是

.header_p1
{
        background: white;
        width: 750px;
        height: 110px;
        margin-bottom: 10px;
}
.header_p1_child
{
        float: none;
        background: white;
        width: 750px;
        height: 110px;
        position: fixed;
        top: 0px;

}

3 个答案:

答案 0 :(得分:8)

您希望将居中标题固定在页面顶部,以便对于较长的页面,内容将在标题下方垂直滚动。

以下是原型HTML代码段:

<div class="wrapper">
    <div class="header">
        <img class="banner" src="http://placehold.it/200x100" />
    </div>
    <div class="content">
        <p>Lorem ipsum dolor ...</p>
    </div>
</div>

我创建了一个div.wrapper块来定义布局的上下文,其中有一些填充等于标题的预期高度。

div.header块包含图像(200x100像素),div.content包含各种文本段落。

布局和样式在以下CSS中定义:

.wrapper {
    outline: 2px dotted blue; /** optional **/

    /** Top padding so that initially, the content is below the header **/
    padding-top: 100px;

}

.header {
    height: 100px;
    width: 400px; /** Use 100% to fill the width of the page **/
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    margin: 0 auto;
    background-color: rgba(0,0,255,0.2);
}

img.banner {
    display: block;
    margin: 0 auto;
} 

.header样式声明高度和宽度,并使用position: fixed将元素的位置固定到视口。对于定位,top: 0将标题放在页面顶部。

要使元素居中,请设置left: 0right: 0并使用margin: 0 auto

div.header中,您可以将图像声明为块类型元素,然后使用margin: 0 auto将其居中。

我在Firefox和Chrome中都检查过它,它按预期工作。这依赖于CSS 2.1所以它应该可以在很多旧的浏览器中运行,也许是IE7,但是我没有对它进行测试,但也许有人可以这样做并做出相应的评论。

小提琴: http://jsfiddle.net/audetwebdesign/q2WRv/

答案 1 :(得分:2)

来源:http://css-tricks.com/quick-css-trick-how-to-center-an-object-exactly-in-the-center/

请勿使用<center>标记,这已过时,应使用CSS

完成
<body>
<div class="header_p1"><img src="header.png"/></div></center>

CSS

.header_p1
{
    background: white;
    width: 750px;
    height: 110px;
    padding-bottom: 10px;
    position: fixed;
    top: 0;
    left: 50%;           /* Start at 50% of browser window */
    margin-left: -325px; /* Go half of width to the left, centering the element */
}

答案 2 :(得分:1)

here中取自为了使图像准确居中,这是一个简单的问题,即应用图像高度的一半的负上边距和图像宽度的一半的负左边距。对于这个例子,像这样:

enter image description here

.centered {
  position: fixed;
  top: 50%;
  left: 50%;
  margin-top: -50px;
  margin-left: -100px;
}

enter image description here

相关问题