css 图片垂直水平居中

709 阅读1分钟

<div class="avatar">
    <img class="avatar-img" src="/static/images/avatar.png">
</div>
  • flex + margin: auto;

.avatar{
  width: 200px;
  height: 200px;
  background-color: #2196f3;
  display: flex;
  .avatar-img{
    width: 100px;
    height: 100px;
    margin: auto;
  }
}

  • position + transform:translate(-50%)

.avatar{
  width: 200px;
  height: 200px;
  background-color: #2196f3;
  position: relative;
  .avatar-img{
    width: 100px;
    height: 100px;
    position: absolute;
    top: 50%;
    left: 50%;
    z-index: 1;
    transform: translate(-50%, -50%);
  }
}

  • display: flex;

.avatar {
  width: 200px;
  height: 200px;
  background-color: #2196f3;
  display: flex;
  justify-content: center;
  align-items: center;
  .avatar-img{
    width: 100px;
    height: 100px;
  }
}