方法一:使用flex布局,父级元素设置justify-content和align-items
<div class="cont">
<div class="item"></div>
</div>
.cont {
100px;
height: 100px;
background: red;
display: flex;
justify-content: center;
align-items: center;
}
.item {
50px;
height: 50px;
background: yellow
}
方法二:使用position和transform属性:这是css3里的样式;缺点:兼容性不好,只支持IE9+的浏览器
<div class="cont">
<div class="item"></div>
</div>
.cont {
100px;
height: 100px;
background: red;
position: relative;
}
.item {
50px;
height: 50px;
background: yellow;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
方法三:使用position和margin属性:兼容性好。缺点:必须知道元素的宽高
<div class="cont">
<div class="item"></div>
</div>
.cont {
100px;
height: 100px;
background: red;
position: relative;
}
.item {
50px;
height: 50px;
background: yellow;
position: absolute;
left: 50%;
top: 50%;
margin-left: -25px;
margin-top: -25px;
}
方法四:使用position和margin属性:兼容性好
<div class="cont">
<div class="item"></div>
</div>
.cont {
100px;
height: 100px;
background: red;
position: relative;
}
.item {
50px;
height: 50px;
background: yellow;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}