Perfect centering with pure CSS

2010-07-24 04:11:08 +08:00
 disinfeqt
有时为了做一个很酷的演示页面,会需要用到绝对居中(水平+垂直)。
如果是像这样写,会有很大的局限性。
最近开始用这个自己摸索出来的方法来居中:

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Perfect Centering</title>
<style>
html {
display:table;
height:100%;
width:100%;
}
body {
display:table-cell;
height:105px;
text-align:center;
vertical-align:middle;
width:418px;
}
</style>
</head>
<body>
<h1>I should've been centered and I'm cool with it.</h1>
</body>
</html>

What about IE? Just fuck off.
5961 次点击
所在节点    分享创造
4 条回复
disinfeqt
2010-07-24 04:12:23 +08:00
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Perfect Centering</title>
<style>
html {
display:table;
height:100%;
width:100%;
}
body {
display:table-cell;
text-align:center;
vertical-align:middle;
}
</style>
</head>
<body>
<h1>I should've been centered and I'm cool with it.</h1>
</body>
</html>

Sorry sorry,哪里来的高度宽度... 囧
airwolf
2010-07-24 06:49:52 +08:00
Wow, 正好可以用到的,看起来很犀利啊!

Thanks :)
disinfeqt
2010-07-24 16:04:07 +08:00
@airwolf Glad to help :)
lianghai
2010-07-24 20:27:13 +08:00
哇靠,感慨,原来“display:”这么牛。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/840

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX