块级元素居中css

1.元素水平、垂直居中
(1)子绝父相(定位)

    <div class="father">
      <div class="son"></div>
    </div>
.father{
  width:100px;
  height:100px;
  background:#000;
  position:relative;
}
.son{
  width:20px;
  height:30px;
  background:#fff;
  position:absolute;
  left: 50%;
  top: 50%;
  translate:-50% -50%;
}

(2)flex布局,父只有一个子元素

.father{
  width:100px;
  height:100px;
  background:#000;
  display: flex;
  justify-content: center;
  align-items: center;
}
.son{
  width: 20px;
  height: 30px;
  background:#fff;
}

posted @ 2022-09-07 10:08  胡同树下  阅读(36)  评论(0)    收藏  举报