一,行内元素:
div{ text-align:center } /*DIV内的行内元素均会水平居中*/
div{ height:30px; line-height:30px } /*DIV内的行内元素均会垂直居中*/
二,块级元素:
div p{margin:0 auto; width:500px} /*块级元素p一定要设置宽度,才能相当于DIV父容器水平居中*/
块级元素垂直居中7种方法
1,table形式居中
<div id="parent">
<div id="child">Content here</div>
</div>
#parent {
display: table;
}
#child {
display: table-cell;
vertical-align: middle;
}
display:table-cell 的元素对宽高敏感,对margin值无反应,响应padding属性
2,absolute 加 margin
<div id="parent">
<div id="child">Content here</div>
</div>
#parent {
position: relative;
}
#child {
position: absolute;
top: 50%;
left: 50%;
height: 30%;
width: 50%;
margin: -15% 0 0 -25%;
}
3,absolute 加 拉伸
<div id="parent">
<div id="child">Content here</div>
</div>
#parent {
position: relative;
}
#child {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
width: 50%;
height: 30%;
margin: auto;
}
4,上下 padding
<div id="parent">
<div id="child">Content here</div>
</div>
#parent {
padding: 5% 0;
}
#child {
padding: 10% 0;
}
5,浮动DIV
<div id="parent">
<div id="floater"></div>
<div id="child">Content here</div>
</div>
#parent {
height: 250px;
}
#floater {
float: left;
height: 50%;
width: 100%;
margin-bottom: -50px;
}
#child {
clear: both;
height: 100px;
}
6,absolute 加 transform(PC有兼容问题)
<div id="parent">
<div id="child">Content here</div>
</div>
#parent {
position: relative;
}
#child {
position: absolute;
width: 100%;
top: 50%;
left: 0;
text-align: center;
transform: translateY(-50%);
}
7,flex 弹性布局居中(PC有兼容问题)
<div id="parent">
<div id="child">Content here</div>
</div>
#parent {
display: flex;
align-items: center;
/*垂直居中*/
justify-content: center;
/*水平居中*/
}