水平居中的方法很简单,一般都是一个margin:0 auto搞定,可是垂直居中就没有那么简单了。首先来讲说垂直居中的几种状况。html
一、文字垂直居中浏览器
文字垂直居中的方法通常是设置高度与行高一致,而后文字就垂直居中了。来看下面的示例:布局
<html> <head> <meta charset="gb2312" /> <title>高度自适应布局</title> <style> p{ height:100px; background-color:#dcdcdc; color:#333; } </style> </head> <body> <div> <p style="line-height:100px;"> 这是一行文字 </p> </div> </body> </html>
其显示效果以下:flex
二、将一个div垂直居中
下面来将一个div设置到整个浏览器的中间,要设置到浏览器的中间,因此咱们就要求页面要占满整个浏览器,因此从html、body要逐层设置其高度为100%。spa
<html> <head> <meta charset="gb2312" /> <title>高度自适应布局</title> <style> html, body{ height: 100%; } div{ width:200px; height:200px; background-color:#dcdcdc; position: relative; top: 50%; /* 向下偏移50% */ transform: translateY(-50%); /* 再向上偏移50% */ } </style> </head> <body> <div> </div> </body> </html>
其效果以下所示:.net
三、CSS3新属性设置居中
若是是CSS3,则能够设置外层的display为flex,而后align-items为center,justify-content为center也能够实现垂直居中的效果。code
<html> <head> <meta charset="gb2312" /> <title>高度自适应布局</title> <style> html, body{ height: 100%; } body{ display: flex; align-items: center; /*定义body的元素垂直居中*/ justify-content: center; /*定义body的里的元素水平居中*/ } div{ width:200px; height:200px; background-color:#dcdcdc; } </style> </head> <body> <div> </div> </body> </html>
效果以下所示:orm
四、绝对定位实现居中
还有一种能够应用绝对定位实现居中的,咱们都知道绝对定位是根据其最近relative、absolute父元素来定位的,使用这种方式,咱们根本都不须要设置那么多的height:100%,只须要将其父元素设置成relative就能够了,想它相对于那个元素居中就相对于哪一个元素居中。来看示例:htm
<html> <head> <meta charset="gb2312" /> <title>高度自适应布局</title> <style> .div_outer{ width:400px; height:400px; border:1px solid blue; position:relative; } .center_middle{ width:200px; height:200px; background-color:#dcdcdc; margin: auto; position: absolute; top: 0; left: 0; bottom: 0; right: 0; } </style> </head> <body> <div class="div_outer"> <div class="center_middle"> </div> </div> </body> </html>
其效果以下:blog
来源文章:
http://blog.csdn.net/freshlover/article/details/11579669
http://www.cnblogs.com/yugege/p/5246652.html