简体   繁体   English

垂直(和水平)居中

[英]Centering things Vertically (and Horizontally)

Why is trying to align something in the center of the viewport (or wrapper) either vertically or horizontally (or both) so painful? 为什么尝试在视口(或包装器)的中心垂直或水平(或两者)对齐某些东西是如此痛苦?

I have tried everything I could find in the past hour, from sites like W3Schools to S/O to MSDN - I just don't know how to do it. 我已经尝试了过去一小时内可以找到的所有内容,从W3Schools到S / O到MSDN等网站 - 我只是不知道该怎么做。 There has to be an easy way to do this. 必须有一个简单的方法来做到这一点。 And WHY can you center a DIV horizontally like this: margin: 0 auto; 为什么你可以像这样水平居中DIV:margin:0 auto; but not vertically? 但不垂直? And why can't you use that same approach with any other element on the page? 为什么不能对页面上的任何其他元素使用相同的方法?

I have a one line sentence (testimonial) that i would like to center vertically and horizontally, how can I do this? 我有一个单行句子(见证),我想垂直和水平居中,我该怎么办?

Roger Johansson wrote an interesting article about it here: http://www.456bereastreet.com/archive/201103/flexible_height_vertical_centering_with_css_beyond_ie7/ Roger Johansson在这里写了一篇有趣的文章: http//www.456bereastreet.com/archive/201103/flexible_height_vertical_centering_with_css_beyond_ie7/

Heres the gist of it: 继承人的要点:

<body>
    <div id="body">
        Content goes here
    </div>
</body>

With this css: 有了这个css:

html, body { width:100%; height:100%; }
html { display:table; }
body {display:table-cell; vertical-align:middle; }
#body { max-width:50em; margin:0 auto; }

This will center both horizontally and vertically and it works in all browsers including IE quirks mode. 这将在水平和垂直中心,它适用于所有浏览器,包括IE怪癖模式。

div{
    width:200px;
    height:200px;
    background:red;
    position:absolute;
    left:50%;
    top:50%;
    margin-left:-100px; /* Negative half the width*/
    margin-top:-100px; /* Negative half the height */
}

Check working example at http://jsfiddle.net/Nt5PU/ 查看http://jsfiddle.net/Nt5PU/上的工作示例

要使文本行居中,请将其CSS line-height属性设置为与包含它的块相同的高度。

Hey its painful, yes it is. 嘿,这很痛苦,是的。 Its stupid that HTML does not by default have these things built in and even in HTML5 one has to use the same hacks. 它的愚蠢,HTML默认情况下没有内置这些​​东西,甚至在HTML5中也必须使用相同的黑客。 But try these solutions you will less regret to re-invent everything http://intensivstation.ch/en/templates/ 但尝试这些解决方案,你将不会后悔重新发明一切http://intensivstation.ch/en/templates/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM