常用的实现元素水平垂直居中的方法

常用的实现元素水平垂直居中的方法

1. 利用绝对定位、设置4个方向上的值都为0,然后设置 margin:auto。由于宽高固定,所有方向实现平分

 <style>
    * {
      margin: 0;
      padding: 0;
    }
    
    html, body, .wrapper {
      width: 100%;
      height: 100%;
    }  /*使父元素有高度*/
    
    .wrapper{
      position: relative;
    }

    .box{
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
      top: 0;
      width: 100px;
      height: 100px;
      margin: auto;
      background-color: coral;
    }
  </style>
</head>
<body>
  <div class="wrapper">
    <div class="box">hello</div>
  </div>
</body>

2. 利用绝对定位,设置top 和 left方向上的值都为 50%,然后利用 transfrom: translate(-50%, -50%);

  <style>
    *{
      padding: 0px;
      margin: 0px;
    }
    
    html,body,.wrapper{
      width: 100%;
      height: 100%;
    }

    .wrapper{
      position: relative;
    }

    .box{
      position: absolute;
      width: 100px;
      height: 100px;
      background-color: coral;
      left: 50%;
      top: 50%;
      transform: translate(-50%,-50%);
    }
  </style>
</head>
<body>
  <div class="wrapper">
    <div class="box">hello</div>
  </div>
</body>
  

以上两种方式的实现效果均为:
在这里插入图片描述

3. 使用display:inline-block; ,然后在父元素上加 text-aligen:center;

 <style>
   *{
      padding: 0px;
      margin: 0px;
    }

    .wrapper{
      width: 500px;
      height: 500px;
      background: yellow;
    }
    
    .wrapper{
      text-align: center;
      line-height: 500px;  
    }

    .box{
      width: 100px;
      height: 100px;
      display: inline-block;
      background-color: aqua;
    }
  </style>
<body>
 <div class="wrapper">
   <div class="box"></div>
 </div>

在这里插入图片描述

4.实现一个div的水平居中,利用margin:0,auto;

<style>
    .box{
      width: 100px;
      height: 100px;
      margin: 0 auto;
      background: aqua;
    }
  </style>
</head>
<body>
  <div class="box">nihao</div>
</body>

在这里插入图片描述

5.实现文本元素的水平垂直居中

 <style>
    .box{
      width: 100px;
      height: 100px;
      margin: 0 auto;
      background: aqua;
      text-align: center;
      line-height: 100px;
    }
  </style>
</head>
<body>
  <div class="box">nihao</div>
</body>

在这里插入图片描述
以上就是我总结的五中实现元素居中的方法,后续如果再学到其它的方法,我会继续补充。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值