css 实现水平垂直居中的三种经常使用方法

css 实现水平垂直居中的三种经常使用方法

首先基本结构样式

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

使里面的span元素(粉色圆点)水平垂直居中于其div父元素(淘宝色正方形)css

实现的效果图以下:

alxU9H.png

下面是经常使用的三种方法:

1.定位

 <style>
      * {
          margin: 0;
          padding: 0;
      }
      .box {
          width: 100px;
          height: 100px;
          background: #f40;
          position: relative;
          margin: 200px auto;
      }
      .box span{
          width: 20px;
          height: 20px;
          background: pink;
          border-radius: 50%;
          position: absolute;
          left: 50%;
          margin-left: -10px;
          top:50%;
          margin-top: -10px;

      }
  </style>

2.flex 设置主轴及侧轴方向居中

<style>
      * {
          margin: 0;
          padding: 0;
      }
      .box {
          width: 100px;
          height: 100px;
          background: #f40;
          margin: 200px auto;
          display: flex;
          justify-content: center;
          align-items: center;
      }
      .box span{
          width: 20px;
          height: 20px;
          background: pink;
          border-radius: 50%;
      }
  </style>

3.最简单,最直接,最牛逼

直接在子元素span下设置 margin : auto;便可
<style>
      * {
          margin: 0;
          padding: 0;
      }
      .box {
          width: 100px;
          height: 100px;
          background: #f40;
          margin: 200px auto;
          display: flex;
      }
      .box span{
          width: 20px;
          height: 20px;
          background: pink;
          border-radius: 50%;
          margin: auto;
      }
  </style>

总结:

以上三种方法在咱们的实际场景中常常会用到,因此咱们要熟练掌握。
还有我我的建议使用后两种,不建议使用第一种,后两种简单,采用flex布局,避免用定位。
相关文章
相关标签/搜索