1

我有一个带有固定标题的页面。我需要将整个页面垂直居中,以使标题始终固定但整个页面垂直居中。

我无法弄清楚,它是如何做到的,因为它不仅仅是搞乱负边距和绝对定位(至少我无法找到一个可行的解决方案......)。我创建了jsFiddle ...

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

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

3 回答 3

1

1)如果您希望内容在标题后留下的空间中垂直居中:请参阅Working Fiddle Tested on: IE10、IE9、IE8、Chrome、FF、Safari

2) 如果您希望内容在视口中垂直居中而不考虑标题:请参阅Working Fiddle Tested on: 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-blocks 元素之间的空格。这导致输出中的空间间隙。使用注释,代码仍然可读,但元素之间没有空格。

于 2013-09-17T23:07:25.547 回答
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>
于 2013-09-17T21:19:57.057 回答
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/

于 2016-01-05T11:57:35.863 回答