
HTML部分:
<div class="container">
</div>
Css部分:
就像下面,只需要给.container三行css规则就可以使它在水平方向和垂直方向均处于居中。
.container {
display: flex;
justify-content: center;
align-items: center;
}
兼容性
这个方法适用于所有现代浏览器- IE10 +,Chrome浏览器,Firefox和Safari(与-webkit- 前缀)。完整的兼容性列表如下:


一个具体实例
height="450" width="600px" scrolling="no" src="//codepen.io/G-Dragon/embed/yJYLLz/?height=450&theme-id=0&default-tab=html,result&embed-version=2" allowfullscreen="true">See the Pen <a href="http://codepen.io/G-Dragon/pen/yJYLLz/">3行Css实现容器水平、垂直居中</a> by G.Dragon (<a href="http://codepen.io/G-Dragon">@G-Dragon</a>) on <a href="http://codepen.io">CodePen</a>.