css或css3元素垂直水平居中
本文章提供以下7种垂直水平居中的方法,具体用哪种见仁见智。
1.利用css3的transform属性,同时将它内部的img垂直居中
<div class="transform"><img src="favicon.ico" /></div>
.transform {
width: 300px;
height: 300px;
text-align: center;
line-height: 300px;
background: #90EE90;
margin: 0 auto;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.transform img {
width: 50px;
height: 50px;
vertical-align: middle;
}
2.Flex垂直水平居中
<div class="flex">
Flex垂直水平居中
</div>
.flex{
font-size: 25px;
height: 200px;
border: 1px solid black;
display: flex;
align-items: center;
justify-content: center;
}
3.利用position:absolute/fixed,设置left、top、margin-left、margin-top的属性
<div class="three"></div>
.three {
position: absolute;/*fixed*/
width: 200px;
height: 200px;
top: 50%;
left: 50%;
margin-top: -100px;
margin-left: -100px;
background: red;
}
4.利用position:absolute/fixed,设置margin:auto
<div class="four"></div>
.four {
position: fixed;
width: 160px;
height: 160px;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
background: pink;
}
5.利用display:table-cell属性使内容垂直居中
<div class="five">内容垂直居中</div>
.five {
display: table-cell;
vertical-align: middle;
text-align: center;
width: 120px;
height: 120px;
background: purple;
}
6.利用display:-webkit-box属性
<div class="six">display:-webkit-box属性</div>
.six {
width: 200px;
height: 200px;
display: -webkit-box;
-webkit-box-pack: center;
-webkit-box-align: center;
background: yellow;
color: black;
}
7.最高大上的一种,利用:before元素
<div class="seven"><div class="content"></div></div>
.seven {
position: fixed;
display: block;
top: 0;
right: 0;
bottom: 0;
left: 0;
text-align: center;
background: rgba(0, 0, 0, .5);
}
.seven:before {
content: '';
display: inline-block;
vertical-align: middle;
height: 100%;
}
.seven .content {
display: inline-block;
vertical-align: middle;
width: 60px;
height: 60px;
line-height: 60px;
color: red;
background: yellow;
}