1、针对单行文本,必须是单行,且高度固定
将line-height和height设置为一样即可实现垂直居中
html
<div class="vertical">content</div>
css
.vertical{
height: 100px;
width: 100%;
line-height: 100px;
margin: 0 auto; // 水平居中
}
2、针对多行元素,元素高度和宽度固定,可以为px也可以为%,使用绝对定位(position: absolute);注意,此方式是实现元素的水平垂直居中,而不是元素里的内容
给需定位的元素设置绝对定位,该内容必须有固定高度height,且样式需要为position:absolute,top:50%和margin-top:-height/2,以此实现垂直居中,同理实现水平居中
html
<div class="vertical">
<div class="item">content</div>
</div>
css
.vertical{
position: relative;
height: 300px;
width: 300px;
}
.item{
height: 100px; // 元素高度必须固定
position: absolute; // 给需定位的元素设置绝对定位
top: 50%; // 相对父级容器顶端偏移父级容器高度50%,此时元素顶端位于父级中间50%的高度处
margin-top: 50px; // 元素又向父级容器顶端上移自身一半(此行往上为实现垂直居中)
width: 100px; // 宽度固定(此行往下为实现水平居中)
left: 50%
margin-left: -50px;
}
3、使用display: table/table-cell; vertical-align: middle;此方法不适合IE6-7以下
html
<div id="container">
<div id="content">content</div>
</div>
css
#container {
height: 300px; // 此方法对height无强制要求
display: table;/*让元素以表格形式渲染*/
}
#content {
display:table-cell;/*让元素以表格的单元素格形式渲染*/
vertical-align: middle;/*使用元素的垂直对齐*/
}
针对IE6-7以下,可使用css hack去实现
4、在居中元素前使用空的div,且居中元素需要清除浮动。另外如果居中元素是放在body中时,还需要对body设置height: 100%
html
<body>
<div id="floater"></div>
<div id="content">Content section</div>
</nody>
css
html,body {
height: 100%
}
#floater{
float: left;
height: 50%;
margin-bottom: -120px; /*值的大小为居中元素高度的一半*/
}
#content{
clear: both; /*清除浮动*/
height:240px;
position: relative;
}
此方法缺点是元素高度被固定死,无法达到内容自适应高度,如果#conten他加上overflow属性,则要么出现滚动条要么内容被切掉
5、使用display: table-cell来实现,同时需要加一个线盒型,用来实现IE下的效果
线盒型最后使用行内标签,如span,不要用块级标签!并把这个线盒型高度设置为100%。此方法类似于方法3,只是对IE下的处理方法做了改变
html
<body>
<p class="table">
<span class="tableCell">Centering multiple lines <br>in a block container.</span>
<!-- IE7以下 -->
<b></b>
</p>
</body>
css
<style>
.table {
display: table;
height: 200px;
width: 200px;
}
.tableCell {
display: table-cell;
vertical-align: middle;
}
/* IE7以下 */
/*
.tableCell{
display:inline-block;
}
b {
display: inline-block;
height:100%;
vertical-align:middel;
width:1px;
}
*/
</style>
6、采用display: inline-block然后借助另一个元素实现居中
html
<body>
<div id="parent">
<div id="vertically_center">
<p>I am vertically centered!</p>
</div>
<div id="extra"><!-- ie comment --></div>
</div>
</body>
css
<style>
html,
body{
height: 100%;
}
#parent {
height: 500px;/*定义高度,让线盒型div#extra有一个参照物,可以是固定值,也可以是百分比*/
border: 1px solid red;
}
#vertically_center,
#extra {
display: inline-block;/*把元素转为行内块显示*/
vertical-align: middle;/*垂直居中*/
}
#extra {
height: 100%; /*设置线盒型为父元素的100%高度*/
}
</style>
7、设置相同的上下padding
html
<div class="columns">
<div class="item">test</div>
</div>
css
.item {
padding-top:30px;
padding-bottom:30px;
}