web前端常见的几种居中方法

1.flex布局实现盒子居中:

将父盒子设为弹性容器,并使用主轴居中属性和侧轴居中属性。

公共结构代码:

<body>
  <div class="demo">
    <div class="box"></div>
  </div>
</body>

 代码示例:

  <style>
    .demo{
      width: 500px;
      height: 500px;
      background-color: #f00;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .box{
      width: 200px;
      height: 200px;
      background-color: #0f0;
    }    
  </style>

2.定位+位移实现盒子居中:

使用定位(父盒子相对定位,子盒子绝对定位)移动父盒子的宽高各一半,再使用位移往回移动子盒子自身的一半。

代码示例:

<style>
    .demo{
      width: 500px;
      height: 500px;
      background-color: #f00;
      position: relative;
    }
    .box{
      width: 200px;
      height: 200px;
      background-color: #0f0;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%,-50%);
    }   
  </style>

3.定位+外边距实现盒子居中:

使用定位(父盒子相对定位,子盒子绝对定位)移动父盒子的一半,再使用外边距移动子盒子的一半。但这种方法的缺点是盒子的大小必须是固定的。

代码示例:

<style>
    .demo{
      width: 500px;
      height: 500px;
      background-color: #f00;
      position: relative;
    }
    .box{
      width: 200px;
      height: 200px;
      background-color: #0f0;
      position: absolute;
      top: 50%;
      left: 50%;
      margin-top: -100px;
      margin-left: -100px;
    } 
  </style>

4.定位+外边距为auto实现盒子居中:

使用定位(父盒子相对定位,子盒子绝对定位)将四个方位名词的值都设为0,margin的值设为auto。

代码示例:

<style>
    .demo{
      width: 500px;
      height: 500px;
      background-color: #f00;
      position: relative;
    }
    .box{
      width: 200px;
      height: 200px;
      background-color: #0f0;
      position: absolute;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
      margin: auto;      
    } 
  </style>

使用频率:前两种方法使用最多(前端开发必会),第三种有致命缺点基本不使用,第四种属于拓展知识范围正经开发不会使用。

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值