在CSS中实现粘性页脚上方的水平和垂直居中

8

如果有一个像Ryan Fait网站上一样高度固定的粘性页脚,是否可以在该页脚上方的空间中水平和垂直居中大小可变的内容?


1
可以再提供一些信息吗?提供一个示例链接会很好。如果这个页面是你想要的,那么请检查那里的代码。我不确定它是否是一个固定页脚而不仅仅是页脚,为什么你想要垂直居中页脚呢?或者你想要将页脚上面的内容居中吗? - benteh
我指的页脚在这里: http://ryanfait.com/sticky-footer/他将页面水平居中于页脚之上,但没有垂直居中。我想要在页面顶部和页脚之间添加垂直居中。 - Dan
所以您有一个包含所有内容(包括页脚)的包装 div。然后您有一个 div,它包含垂直居中的任何内容,除了页脚。这是您的意思吗? - benteh
没有针对可变大小内容的答案? - Dan
2个回答

5

我建议看一下Bobby van der Sluis在A List Apart上关于页脚的文章。

他文章末尾的示例#7展示了一个垂直居中的块。它依赖于脚本,但是真的很小。

edit你也可以使用单元格表来实现垂直居中。将其与Ryan Fait的粘性页脚相结合,您会得到像这样的东西:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
    <style type="text/css">        

    /* Original Sticky Footer: http://ryanfait.com/sticky-footer/ */

    html, body {
        margin: 0;
        height: 100%;
        width: 100%;
        }

    #footer {
        margin-top: -150px;
        height: 150px;
        }

    #footer {
        background: #bbd;
        }

    .block {
        width: 300px;
        padding: 20px;
        background: yellow;
        margin: 0 auto 150px; /* height of #footer */
        }

</style>
</head>
<body>

<table width="100%" height="100%" border="0" cellpadding="0" cellspacing="0">

    <tr><td>

        <div class="block">
            <h1>Vertically Centered!</h1>
            <p>This block will remain centered. Just needs that one table cell wrapping.</p>
        </div>

    </td></tr>
</table>

<div id="footer">Footer Content here</div>

</body>
</html>

我总觉得使用表格很不舒服,但我想对于像这样的东西,那就是必须的。谢谢! :) - Dan

0

好的,那么您可以设置内容的垂直对齐方式:

.verticalalign{
width:270px;
height:150px;
position:absolute;
left:50%;
top:50%;
margin:-75px 0 0 -135px;

}


问题在于我不知道内容的大小,无法指定绝对值,因此出现了问题。 - Dan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接