CSS3实现水平垂直居中

来源:互联网 发布:快飞机域名 编辑:程序博客网 时间:2024/05/14 02:00

水平垂直居中的制作大家都有碰到过,水平居中方法好处理,但是垂直居中的话还是让很多人头痛过,我也碰到很多盆友来询问如何让元素水平垂直居中。前面也专门讨论过如何让图片,单行文本和多行文本实现各种浏览器的水平垂直居中的方案。

前面在《CSS制作图片水平垂直居中》和《CSS制作水平垂直居中对齐》两篇文章中和大家一起探讨过多种实现方法,以及兼容ie浏览器。这次在iPhone项目中实现弹出窗口水平垂直居中,总不是很理想,后来采用了一种纯CSS3的实box方法实现水平垂直居中,现将实现的代码片段贴出与大家分享:

HTML Markup

<div class="center">  <img src="http://www.w3cplus.com/sites/default/files/source/webdesign.jpg" alt="" /></div><div class="center">  <div class="text">我就一行文字</div></div><div class="center">  <div class="text">    我是多行文字<br />    我是多行文字  </div></div>

CSS Code

.center {  width: 300px;  height: 200px;  padding: 10px;  border: 1px solid #ccc;  margin: 20px auto;  display: -webkit-box;  -webkit-box-orient: horizontal;  -webkit-box-pack: center;  -webkit-box-align: center;  display: -moz-box;  -moz-box-orient: horizontal;  -moz-box-pack: center;  -moz-box-align: center;  display: -o-box;  -o-box-orient: horizontal;  -o-box-pack: center;  -o-box-align: center;  display: -ms-box;  -ms-box-orient: horizontal;  -ms-box-pack: center;  -ms-box-align: center;  display: box;  box-orient: horizontal;  box-pack: center;  box-align: center;}.center img,.text {  border: 1px solid #dedede;  padding: 2px;}

效果:

实现水平垂直居中的关键代码:

 display: -webkit-box;  -webkit-box-orient: horizontal;  -webkit-box-pack: center;  -webkit-box-align: center;  display: -moz-box;  -moz-box-orient: horizontal;  -moz-box-pack: center;  -moz-box-align: center;  display: -o-box;  -o-box-orient: horizontal;  -o-box-pack: center;  -o-box-align: center;  display: -ms-box;  -ms-box-orient: horizontal;  -ms-box-pack: center;  -ms-box-align: center;  display: box;  box-orient: horizontal;  box-pack: center;  box-align: center;

由于flexbox是CSS3的一个新属性,目前支持的浏览器仅:IE10+, Firefox 2+, Chrome 4+, Safari 3.1+。其他实现方法,大家感兴趣可以参阅:《CSS制作图片水平垂直居中》和《CSS制作水平垂直居中对齐》两篇文章。

如需转载烦请注明出处:http://www.w3cplus.com/codes/vertically-center-content-with-css3.html