CSS之水平垂直居中的几种方法

一、绝对定位+translate

<style>
    article {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 300px;
      height: 300px;
      background-color: rgb(87, 31, 31);
    }
  </style>
<body>
  <article>
    <div></div>
  </article>
</body>

二、flex

<style>
    article {
        display: flex;
        width: 100vw;
        height: 100vh;
        justify-content: center;
        align-items: center;
    }
    div {
        width: 200px;
        height: 200px;
        background: #000;
    }
</style>
</head>

<body>
<article>
    <div></div>
</article>
</body>

三、flex+margin-auto

<style>
  article {
    margin: 0;
    display: flex;
    height: 100vh;
    width: 100vw;
  }

  div {
    width: 100px;
    height: 100px;
    background: #000;
    margin: auto;
  }
</style>

<body>
  <article>
    <div></div>
  </article>
</body>

四、grid

  <style>
    main {
      height: 100vh;
      width: 100vw;
      display: grid;
    }
    div {
      width: 100px;
      height: 100px;
      background: #000;
      justify-self: center;
      align-self: center;
    }
  </style>
</head>
<body>
  <main>
    <div></div>
  </main>
</body>

五、绝对定位

<style>
  article {
    width: 100vw;
    height: 100vh;
  }
  div {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    width: 100px;
    height: 100px;
    background: #000;
  }
</style>

<body>
  <article>
    <div></div>
  </article>
</body>

...待完善

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容