CSS3如何实现水平垂直居中?
2022-06-23 584热度
属于CSS分类
摘要:水平垂直居中的制作大家都有碰到过,水平居中方法好处理,但是垂直居中的话还是让很多人头痛过,我也碰到很多盆友来询问如何让元素水平垂直居中。前面也专门讨论过如何让图片,单行文本和多行文本实现各种浏览器的水平垂直居中的方案。 前面在CSS制作图片水平垂直居中》和《CSS制作水平垂直居中对齐》两篇文章中和大家一起探讨过多种实现方法,以及兼容ie浏览器。这次在iPhone项目中实现弹出窗口水平垂直居中,总不是很理想,后来采用了一种纯CSS3的实...
水平垂直居中的制作大家都有碰到过,水平居中方法好处理,但是垂直居中的话还是让很多人头痛过,我也碰到很多盆友来询问如何让元素水平垂直居中。前面也专门讨论过如何让图片,单行文本和多行文本实现各种浏览器的水平垂直居中的方案。
前面在CSS制作图片水平垂直居中》和《CSS制作水平垂直居中对齐》两篇文章中和大家一起探讨过多种实现方法,以及兼容ie浏览器。这次在iPhone项目中实现弹出窗口水平垂直居中,总不是很理想,后来采用了一种纯CSS3的实box方法实现水平垂直居中,现将实现的代码片段贴出与大家分享:
HTML Markup
-
<divclass="center">
-
<imgsrc="http://www.w3cplus.com/sites/default/files/source/webdesign.jpg"alt=""/>
-
</div>
-
<divclass="center">
-
<divclass="text">我就一行文字</div>
-
</div>
-
<divclass="center">
-
<divclass="text">
-
我是多行文字<br/>
-
我是多行文字
-
</div>
-
</div>
CSS Code
-
.center{
-
width:300px;
-
height:200px;
-
padding:10px;
-
border:1pxsolid#ccc;
-
margin:20pxauto;
-
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;
-
}
-
.centerimg,
-
.text{
-
border:1pxsolid#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;