让div盒子居中

发布时间 2023-12-26 11:51:50作者: 崛起崛起
<template>
  <!-- <div class="about">
    <h1>This is an one page</h1>
  </div> -->
  <div class="about">
    <!-- 1.给盒子设置宽高,然后用margin:0 auto; -->
    <div class="one">第一种:居中</div>
    <!-- flex布局 -->
    <div class="two">第二种:居中</div>
    <!-- 让子盒子居中 -->
    <div class="three">
      <div class="son">第三种:居中</div>
    </div>
    <div class="fourth">
      <div class="son">第四种:居中</div>
    </div>
  </div>
</template>


<script>
export default {};
</script>

<style lang="less" scoped>
.one {
  width: 300px;
  height: 300px;
  margin: 0 auto;
  background-color: antiquewhite;
}
.two {
  display: flex;
  justify-content: center;
  background-color: rgb(214, 134, 29);
}
.three {
  position: relative;
  width: 600px;
  height: 600px;
  background-color: rgb(45, 29, 214);
  .son {
    position: absolute;
    width: 200px;
    height: 200px;
    top: 50%; /*盒子左上角的那个点在页面正中间*/
    left: 50%;
    transform: translateX(-50%) translateY(-50%); /*不需要知道盒子宽度*/
    background-color: rgb(29, 214, 45);
  }
}
.fourth {
  position: relative;
  width: 600px;
  height: 600px;
  background-color: rgb(214, 29, 118);
  .son {
    position: absolute;
    width: 200px;
    height: 200px;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    background-color: rgb(202, 214, 29);
  }
}
</style>