一个盒子垂直水平居中的3中方法方法

本文介绍了如何使用相对定位、flex布局和grid布局将盒子元素垂直和水平居中,分别通过absolute定位、justify-content和align-items属性,以及grid-template-areas来实现不同效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.相对定位和绝对定位

2.flex布局

3.gird布局

<!-- ##CSS
###1.一个盒子垂直水平居中有哪些方法?(2~3种方法) -->
<template>
  <div id="app">
      <!-- 1相对定位 -->
  <!-- <div class="box1">
    <div class="contant1"></div>
  </div> -->
  <!-- 2 flex布局 -->
  <!-- <div class="box2">
    <div class="contant2"></div>
  </div> -->
  <!-- 3. gird布局 -->
  <div class="box3">
    <div class="contant3"></div>
  </div>
  </div>
</template>

<style scoped>
    html ,body ,#app{
        width: 100%;
        height: 100%;
        padding: 0;
        margin: 0;
        box-sizing: border-box;
      }
  
    .box1{
        width: 100%;
        height: 100%;
        background-color: skyblue;
        position: relative;
        
    }
.contant1{
position: absolute;
background-color: rgb(207, 157, 18);
height: 300px;
width: 300px;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
.box2{
    height: 100%;
    background-color: rgb(95, 225, 214);
    display: flex;
    justify-content: center;
    align-items: center;
}
.contant2{
background-color: rgb(16, 149, 100);
height: 300px;
width: 300px;
}
.box3 {
    display: grid;
    height: 100%;
    place-items: center;
    background-color: rgb(126, 34, 176);
    }
    .contant3{
        background-color: rgb(212, 111, 17);
        height: 300px;
        width: 300px;
        }
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值