用CSS集中元素的最不可怕的方法是什么? [英] What is the least horrible way to center an element with CSS?

查看:99
本文介绍了用CSS集中元素的最不可怕的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有html这样的:

<!DOCTYPE html> 
<head>
    <meta charset="utf-8">

    <!--[if lte IE 8]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
</head> 

<body>

<header>
  <h1>Some title thing, who knows</h1>
  <nav>
    <ul>
      <li><a href="one/">One</a></li>
      <li><a href="two/">Two</a></li>
      <li><a href="three/">Three</a></li>
    </ul>
  </nav>
</header>

</body>
</html>

如果我给 header 宽度,它水平居中。

If I give header an auto margin and a width, it's horizontally centered. What's the least horrible way to ensure that it's vertically centered, as well?

我知道以下文章提供了一些主题的讨论:

I am aware of the following articles which provide some discussion of the topic:

  • http://blog.themeforest.net/tutorials/vertical-centering-with-css/
  • http://www.vanseodesign.com/css/vertical-centering/
  • http://www.jakpsatweb.cz/css/css-vertical-center-solution.html
  • http://www.brunildo.org/test/vertmiddle.html

推荐答案

由于这个问题被标记为 CSS3 ,这里是一个最不可怕的解决方案使用CSS3 flexbox。很遗憾,只有最新版本的Safari,Chrome和Firefox支持它。

Since this question was tagged CSS3, here's a "least horrible" solution using CSS3's "flexbox". Unfortunately only recent versions of Safari, Chrome and Firefox support it.

html, body {
  margin:0;
  padding:0;
  height:100%;
  background:#eee;
}
header {
  width:30em;
  background:#fff;
}
body {  
  display:box;
  box-pack:center;
  box-align:center;
  box-orient:horizontal;
}

更完整的演示

A more complete demo can be found here.

这篇关于用CSS集中元素的最不可怕的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆