css垂直居中的8种方法

第一种===>绝对定位配合动画

   body {
    width: 100vw;
    height: 100vh;
    position: relative;
  }

  div {
    width: 100px;
    height: 100px;
    background-color: red;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50px, -50px);
  } 

第二种====>固定定位配合动画

  body {
    width: 100vw;
    height: 100vh;
  }

  div {
    width: 100px;
    height: 100px;
    background-color: red;
    position: fixed;
    left: 50%;
    top: 50%;
    transform: translate(-50px, -50px);
  } 

第三种====>绝对定位配合margin:auto

  body {
    width: 100vw;
    height: 100vh;
    position: relative;
  }

  div {
    width: 100px;
    height: 100px;
    background-color: red;
    position: absolute;
    left: 0;
    top: 0;
    bottom: 0;
    right: 0;
    margin: auto;
  } 

第四种==>display: flex;(一维布局)

  body {
    width: 100vw;
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  div {
    width: 100px;
    height: 100px;
    background-color: red;
  }

第五种==>display: grid;(二维布局)

  body {
    width: 100vw;
    height: 100vh;
    display: grid;
    justify-content: center;
    align-items: center;
  }

  div {
    width: 100px;
    height: 100px;
    background-color: red;
  } 

第六种==>display: grid;(二维布局)

  body {
    width: 100vw;
    height: 100vh;
    display: grid;
  }

  div {
    width: 100px;
    height: 100px;
    background-color: red;
    justify-self: center;
    align-self: center;
  }

第七种==>display: grid;(二维布局)最简单

  body {
    width: 100vw;
    height: 100vh;
    display: grid;
  }

  div {
    width: 100px;
    height: 100px;
    background-color: red;
    margin: auto;
  }

第八种==>display: flex;(一维布局)最简单

  body {
    width: 100vw;
    height: 100vh;
    display: flex;
  }

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

推荐阅读更多精彩内容