垂直居中页面内容

Pie*_*ter 7 html css

我知道如何用CSS水平居中整个页面.但有没有办法垂直居中页面?像这样......


例


mu *_*ort 11

你也可以劫持CSS display: tabledisplay: table-cell为此目的.HTML将是这样的:

<body>
    <div id="body">
        <!-- Content goes here -->
    </div>
</body>
Run Code Online (Sandbox Code Playgroud)

而CSS:

html,
body {
    width: 100%;
    height: 100%;
}
html {
    display: table;
}
body {
    display: table-cell;
    vertical-align: middle;
}
Run Code Online (Sandbox Code Playgroud)

如果你想要水平居中,那么添加:

#body {
    max-width: 1000px; /* Or whatever makes sense for you. */
    margin: 0 auto;
}
Run Code Online (Sandbox Code Playgroud)

有人会称之为滥用CSS但是:

  • 它几乎可以在任何地方使用.
  • 需要最少的标记和样式.
  • CSS的垂直对齐值得一些滥用; 垂直对齐不应该要求它进行黑客攻击,扭曲和绝对大小调整.

参考文献:


Fra*_*ona 9

MicroTut上有一篇很棒的文章可以做到这一点http://tutorialzine.com/2010/03/centering-div-vertically-and-horizo​​ntally/

以CSS为中心:

.className{
    width:300px;
    height:200px;
    position:absolute;
    left:50%;
    top:50%;
    margin:-100px 0 0 -150px;
}
Run Code Online (Sandbox Code Playgroud)

以JQuery为中心:

$(window).resize(function(){

    $('.className').css({
        position:'absolute',
        left: ($(window).width() - $('.className').outerWidth())/2,
        top: ($(window).height() - $('.className').outerHeight())/2
    });

});

// To initially run the function:
$(window).resize();
Run Code Online (Sandbox Code Playgroud)

你可以在这里看到一个演示