您的位置:首页 > Web前端 > CSS

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: