在下面的演示代码中,用到的html结构为:
<div class="content">
<div class="center"></div>
</div>
方法一:positoin+margin
.content{
height: 200px;
width: 200px;
background-color: #ccc;
position: relative;
}
.center{
width: 100px;
height: 100px;
background-color: pink;
margin: auto;
position:absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
}
方法二:display:tell-cell;
.content{
height: 200px;
width: 200px;
background-color: #ccc;
display: table-cell;
vertical-align: middle;
text-align: center;
}
.center{
display: inline-block;
width: 100px;
height: 100px;
background-color: pink;
vertical-align: middle;
}
方法三:display:flex;align-items:center;justify-content:center;
.content{
height: 200px;
width: 200px;
background-color: #ccc;
display: flex;
align-items: center;
justify-content: center;
}
.center{
background-color: pink;
width: 100px;
height: 100px;
}
方法四:display:flex;margin:auto;(主要适用移动端)
.content{
height: 200px;
width: 200px;
background-color: #ccc;
display: flex;
}
.center{
background-color: pink;
width: 100px;
height: 100px;
margin: auto;
}
方法五:纯position
.content{
height: 200px;
width: 200px;
background-color: #ccc;
position: relative;
}
.center{
background-color: pink;
width: 100px;
height: 100px;
position: absolute;
left: 50px;
top: 50px;
}
content{
height: 200px;
width: 200px;
background-color: #ccc;
position: relative;
}
.center{
background-color: pink;
width: 100px;
height: 100px;
position: absolute;
left: 50%;
margin-left: -50px;//-1/2宽度
top: 50%;
margin-top: -50px;//-1/2高度
}