垂直定心,带固定头

时间:2013-09-17 20:44:08

标签: html css css-position vertical-alignment fixed

我有一个固定标题的页面。我需要整个页面以一种方式居中,其方式是标题始终是固定的,但整个页面是以verticaly为中心的。

我无法弄清楚,如何做到这一点,因为它不仅仅需要利用负边距和绝对定位(至少我无法找到有效的解决方案......)。我创建了jsFiddle ...

系统要我添加一些代码,所以这里是你可以在jsFiddle中看到的基本结构

<body>
    <div id="header"><h1>HEADER</h1></div>
    <div id="content">
        <p>This is some content.</p>
    </div>
</body>

3 个答案:

答案 0 :(得分:1)

1)如果您希望内容在标题后面的空格中垂直居中:请参阅Working Fiddle 测试: IE10,IE9,IE8,Chrome,FF ,Safari

2)如果您希望内容在视口中垂直居中而不管标题:请参阅Working Fiddle 测试: IE10,IE9,IE8,Chrome,FF, Safari浏览器

这两个示例都是相同的HTML标记,区别在于CSS(第二个更简单,但结果更加丑陋)

<强> HTML

<div id="header"><h1>YOUR HEADER</h1></div>
<div id="container"><!-- only that container shall be scrollable -->
    <span class="centerer"></span><!-- this comment is important
    --><div id="content">
        YOUR CONTENT
    </div>
</div>

注意:评论很重要,因为新行被视为inline-block元素之间的空格。这导致输出中的空隙。 使用注释时,代码仍然可读,但元素之间没有空格。

答案 1 :(得分:0)

我不确定你想用它做什么..这适用于现代浏览器但不适用于所有浏览器..

问题通常是元素没有固定的高度。我们不知道屏幕高度(以像素为单位),因此高度必须是动态的。较旧的浏览器在填充之前不会给元素提供一定的高度。

http://jsfiddle.net/Mz6hy/25/

在Chrome,Safari和Firefox中对此进行了测试..

<head>
    <style>
    body
    {
        width           : 100%;
        background      : #fff;
        margin          : 60px 0 -60px 0;
    }
    h1
    {
        text-align      : center;
    }
    #content 
    {
        position        : absolute;
        top             : 50%;
        height          :100px;
        margin-top      :-50px;
    }
    #footer 
    {
        position        :absolute;
        top             :100%;
        height          :50px;
        margin-top      :-50px;
    }
    </style>
</head>
<body>
    <h1>HEADER</h1>
    <div id="content">
        <p>
            This is some content.<br/>
            I want it to be verticaly centered along with the fixed header. The header should always be fixed, but it should be placed in a way that the overall page is verticaly centered.
        </p>
        <p>
            Some more content
        </p>
    </div>
    <div id="footer">Editional content</div>
</body>

答案 2 :(得分:0)

现在可以通过flexbox和主容器上100vh的测量非常简单地实现。

<强> CSS:

height: 100vh;
display: flex;
display: -webkit-flex;
justify-content: center;
-webkit-justify-content: center;
flex-direction: column;
-webkit-flex-direction: column;

查看完整演示:https://jsfiddle.net/f8syhrkv/

相关问题