水平垂直居中

绝对定位

绝对定位 + calc

子元素定宽高。

<style>
  #parent {
    width: 300px;
    height: 300px;
    background: #ccc;
    position: relative;
  }

  #child {
    width: 100px;
    height: 100px;
    background: #c9394a;
    position: absolute;
    left: calc(50% - 50px);
    top: calc(50% - 50px);
  }
</style>

<div id="parent">
  <div id="child"></div>
</div>

绝对定位 + 负 margin

子元素定宽高。

<style>
  #parent {
    width: 300px;
    height: 300px;
    background: #ccc;
    position: relative;
  }

  #child {
    width: 100px;
    height: 100px;
    background: #c9394a;
    position: absolute;
    left: 50%;
    top: 50%;
    margin-left: -50px;
    margin-right: -50px;
  }
</style>

<div id="parent">
  <div id="child"></div>
</div>

绝对定位 + transform

<style>
  #parent {
    width: 300px;
    height: 300px;
    background: #ccc;
    position: relative;
  }

  #child {
    width: 100px;
    height: 100px;
    background: #c9394a;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
  }
</style>

<div id="parent">
  <div id="child"></div>
</div>

绝对定位 + 上下左右 0 + margin: auto

子元素定宽高。

<style>
  #parent {
    width: 300px;
    height: 300px;
    background: #ccc;
    position: relative;
  }

  #child {
    width: 100px;
    height: 100px;
    background: #c9394a;
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    margin: auto;
  }
</style>

<div id="parent">
  <div id="child"></div>
</div>

Flex

<style>
  #parent {
    width: 300px;
    height: 300px;
    background: #ccc;
  
    display: flex;
    justify-content: center;
    align-items: center;
  
    /**
    flex-wrap: wrap;
    align-content: center;
    **/
  }
  
  #child {
    width: 100px;
    height: 100px;
    background: #c9394a;
  
    /*align-self: center;*/
  }
</style>

<div id="parent">
  <div id="child"></div>
</div>
<style>
  #parent {
    width: 300px;
    height: 300px;
    background: #ccc;
  
    display: flex;
  }
  
  #child {
    width: 100px;
    height: 100px;
    background: #c9394a;
  
    margin: auto;
  }
</style>

<div id="parent">
  <div id="child"></div>
</div>

Grid

<style>
  #parent {
    width: 300px;
    height: 300px;
    background: #ccc;
  
    display: grid;
  
    /*以下两组排列组合均可*/
  
    /** 
    justify-content: center;
    justify-items: center;
  
    align-content: center;
    align-items: center;
    **/
  }
  
  #child {
    width: 100px;
    height: 100px;
    background: #c9394a;
  
    justify-self: center;
    align-self: center;
  }
}
</style>

<div id="parent">
  <div id="child"></div>
</div>
Last Updated:
Contributors: Vsnoy