CSS之实现水平垂直居中(一)

58 阅读1分钟

利用定位+margin:auto

  • 父元素相对定位,有固定宽高
  • 子元素绝对定位,有固定宽高,top、left、right、bottom设置为0
  • 子元素margin:auto
<style>
.father{
    width:500px;
    height:300px;
    border:1px solid #0a3b98;
    position: relative;
}
.son{
    width:100px;
    height:40px;
    background: #f0a238;
    position: absolute;
    top:0;
    left:0;
    right:0;
    bottom:0;
    margin:auto;
}
</style>
<div class="father">
    <div class="son"></div>
</div>    

效果:

image.png