css垂直居中的几种方法
2016-03-17 23:41
686 查看
1、单行文本居中
html<p>content</p>
css
p { height: 30px; line-height: 30px; }
要点:
height和
line-height值保持一致
用处: button、图片、单行文本内容居中
局限:无法用于多行元素
2、div容器固定高度居中
html<div id="wrapper"> <div class="container"> <p>first paragraph</p> <p>second paragraph</p> </div> </div>
css
#wrapper { height: 200px; width: 300px; background: #ccc; position: relative; } .container { height: 100px; width: 200px; position: absolute; top: 50%; left: 50%; margin-top: -50px; //height的一半 margin-left: -100px; //width的一半 background: #f00; }
如图
要点:给要居中的容器设置
position: absolute,
top: 50%,
margin-top: -height/2(即高度的一半)(水平居中同上)
用处: 多行元素居中对齐,用于页面在最中间的布局
局限:需要固定的高度(即大小要确定)、父元素需要相对定位;当内容大于height时,内容溢出,无法居中;如果overflow:auto,会出现滚动条,如果overflow:hidden,内容被切断
3、模拟表格居中
html<div id="wrapper"> <div class="container"> <p>first paragraph</p> <p>second paragraph</p> </div> </div>
css
#wrapper { height: 200px; display: table; background-color: #f00; } .container { display: table-cell; vertical-align: middle; }
如图
要点:父元素
display: table,当前元素
display: table-cell,并设置
vertical-align: middle
用处:用于高度可以随内容动态改变
局限:不支持IE6-7
4、容器前添加空div
html<div id="wrapper"> <div class="empty"></div> <div class="container"></div> </div>
css
#wrapper { height: 200px; background-color: #ccc; } .empty { height: 50%; //相对于父元素的一半 margin-bottom: -50px; //.container的height的一半 } .container { height: 100px; background-color: #f00; }
如图
要点:在容器前添加空div,并为其设置
height: 50%(父元素高度一半),
margin-bottom为容器高度一半
用处和局限同方法2
相关文章推荐
- css3总结笔记
- 盘点8种CSS实现垂直居中水平居中的绝对定位居中技术
- CSS实现垂直、水平居中方式
- css投影效果
- css实现文字一行居中,多行左对齐
- cssAndHtml
- css3学习--css3动画详解二(3d效果)
- CSS记录-1-ID和类选择符
- css选择器权重
- css 选择器优先级的计算过程
- 详解 CSS 属性 - 伪类和伪元素的区别
- CSS3 颜色值RGBA表示方式
- CSS3 线性渐变(linear-gradient)
- QComboBox 右侧下拉按钮qss样式设置
- 我的头像——DIV+CSS3制作哆啦A梦头像
- 一言不合敲代码(1)——DIV+CSS3制作哆啦A梦头像
- 修改博客园博客样式
- CSS3 不定宽高水平居中
- css把超出的部分显示为省略号的方法兼容火狐
- 探究CSS line-height属性