结合CSS3的新特性来总结垂直居中的实现方法
结合CSS3的新特性来总结垂直居中的实现方法
发布时间:2016-12-27 来源:查字典编辑
摘要:0.单行内容的居中只考虑单行是最简单的,无论是否给容器固定高度,只要给容器设置line-height和height,并使两值相等,再加上ov...

0.单行内容的居中

只考虑单行是最简单的,无论是否给容器固定高度,只要给容器设置 line-height 和 height,并使两值相等,再加上 over-flow: hidden 就可以了

CSS Code复制内容到剪贴板 .middle-demo-1{ height:4em; line-height:4em; overflow:hidden; }

优点:

(1). 同时支持块级和内联极元素

(2). 支持所有浏览器

缺点:

(1). 只能显示一行

(2). IE中不支持<img>等的居中

要注意的是:

(1). 使用相对高度定义你的 height 和 line-height

(2). 不想毁了你的布局的话,overflow: hidden 一定要

为什么?

请比较以下两个例子:

XML/HTML Code复制内容到剪贴板 <pstyle="background:#900;color:#00f;font:bold12px/24pxHelvertica,Arial,sans-serif;height:24px;width:370px;">Loremipsumdolorsitamet,consectetueradipiscingelit.</p> <br/> <br/> <pstyle="background:#090;color:#00f;font:bold12px/2emHelvertica,Arial,sans-serif;height:2em;width:370px;overflow:hidden;">Loremipsumdolorsitamet,consectetueradipiscingelit.</p>

上一个高度是用的绝对单位px,并且没有隐藏溢出,下一个高度用的单位是相对单位em,并且隐藏了溢出。如果你的浏览器支持放大字体,那么尽情地放大字体,看看会出现什么效果。

1.使用position:absolute(fixed),设置left、top、margin-left、margin-top的属性;

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; rightright:0; bottombottom:0; left:0; margin:auto; }

3.利用display:table-cell属性使内容垂直居中;

CSS Code复制内容到剪贴板 .box{ display:table-cell; vertical-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-items:center; -moz-align-items:center; align-items:center; }

推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
相关阅读
网友关注
最新 Div+Css教程学习
热门 Div+Css教程学习
网页设计子分类