0.单行内容的居中
只考虑单行是最 简单 的,无论 是否 给容器固定高度,只要给容器设置 line-h ei ght 和 height,并使两值相等,再加上 over-flow: hidden 就可以了
CSS Code 复制内容到剪贴板
. middle -demo-1{ &nbs p; height : 4em; line-height : 4em; overflow : hidden ; }
优点:
(1). 同时支持块级和内联极元素
(2). 支持所有浏览器
缺点:
(1). 只能显示一行
(2). IE中不支持< img >等的居中
要注意的是:
(1). 使用相对高度定义你的 height 和 line-height
(2). 不想 毁了你的布局的话,overflow: hidden 一定要
为什么?
请比较以下两个例子:
XM L/HT ML Code 复制内容到剪贴板
< p style = "background: # 900; color: #00f; font: bold 12px/24px Helvertica,Arial,sans -s erif; height:24px; width:370px;" > Lorem ipsum dolor s IT am et, consectetuer adipiscing elit. </ p > < br /> < br /> < p style = "background: #090; color: #00f; font: bold 12px/2em Helvertica,Arial,sans-serif; height:2em; width:370px; overflow: hidden;" > Lorem ipsum dolor sit amet, consectetuer adipiscing elit. </ p >
上一个高度是用的绝对单位px,并且没有隐藏溢出,下一个高度用的单位是相对单位em,并且隐藏了溢出。如果你的浏览器支持放大字体,那么尽情地放大字体,看看会出现什么效果。
1.使用position:absolute(fixed),设置left、top、m arg in-left、mar gin -t op的属性;
CSS Code 复制内容到剪贴板
.box{ position : absolute ; /*或fixed*/ top :50%; left :50%; margin-top :- 100px ; margin-left :- 200px ; }
2. 利用 position:fixed(absolute)属性,margin:auto这个必须不要忘记了;
CSS Code 复制内容到剪贴板
.box{ position : absolute ;或 fixed top :0; right right :0; bottom bottom :0; left :0; margin : auto ; }
3.利用dis@R_ 360 _2266@:table-cell属性使内容垂直居中;
CSS Code 复制内容到剪贴板
.box{ display : table-cell ; vert ical -align : middle ; text-align : center ; width : 120px ; height : 120px ; background : purple ; }
4.使用css3的 新属性 transform:translate(x,y)属性;
CSS Code 复制内容到剪贴板
.box{ position : absolute ; transform: translate(50%,50%); - webkit -transform:translate(50%,50%); -moz-transform:translate(50%,50%); -ms-transform:translate(50%,50%); }
5.最高大上的一种,使用:before元素;
CSS Code 复制内容到剪贴板
.box{ position : fixed ; display : block ; background :rgba(0,0,0,.5); } .box:before{ content : '' ; display : inline - block ; vertical-align : middle ; height :100%; } .box. content { width : 60px ; height : 60px ; line-height : 60px ; color : red ;
6.Flex布局;
CSS Code 复制内容到剪贴板
.box{ display : -webkit-box; display : -webkit-flex; display : -moz-box; display : -moz-flex; display : -ms- flexbox ; display : flex; 水平居中 -webkit-box-align: center ; -moz-box-align: center ; -ms-flex-pack: center ; -webkit- justify - content : center ; -moz- justify - content : center ; justify - content : center ; 垂直居中 -webkit-box-pack: center ; -moz-box-pack: center ; -ms-flex-align: center ; -webkit-align -i tems: center ; -moz-align-items: center ; align-items: center ; }
总结
以上是 为你收集整理的 结合CSS3的新特性来总结垂直居中的实现方法 全部内容,希望文章能够帮你解决 结合CSS3的新特性来总结垂直居中的实现方法 所遇到的问题。
如果觉得 网站内容还不错, 推荐好友。
查看更多关于结合CSS3的新特性来总结垂直居中的实现方法的详细内容...