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

这个问题在这里已经有了答案:

  • 居中位置:固定元素11个答案

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

    这是原型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块包含一个图像( div.content像素), 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将元素的位置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/


    资料来源: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 */
    }
    

    Orignally从这里为了让图像完全居中,这是一个简单的问题,即应用图像高度的一半的负顶边距和一半图像宽度的负左边距。 对于这个例子,像这样:

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

    链接地址: http://www.djcxy.com/p/75795.html

    上一篇: Center header element with position fixed to top of page

    下一篇: Position a block element in the bottom