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佈局,避免用定位。
相關文章
相關標籤/搜索