Skip to content
  • 方案1 position

    html
    <style>
      /* 方案1 */
      #parent {
        width: 200px;
        height: 200px;
        background-color: #bfa;
        position: relative;
      }
    
      #demo {
        width: 100px;
        height: 100px;
        background-color: pink;
        position: absolute;
    
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        margin: auto;
    
        /* 或者 */
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
    
        /* 已知自身宽高 */
        top: 50%;
        left: 50%;
        margin-top: -50px;
        margin-left: -50px;
    
        /* 已知自身宽高 */
        top: calc(50% - 50px);
        left: calc(50% - 50px);
      }
    </style>
  • 方案2 flex

    html
    <style>
    #parent {
      width: 200px;
      height: 200px;
      background-color: #bfa;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    
    #demo {
      width: 100px;
      height: 100px;
      background-color: pink;
    }
    </style>
  • 方案3 grid

    html
    <style>
      #parent {
        width: 200px;
        height: 200px;
        background-color: #bfa;
        display: grid;
        /* 该属性是 align-items、justify-items 属性的简写。如果未提供第二个值,则第一
        个值作为第二个值的默认值。 */
        place-items: center center;
      }
    
      #demo {
        width: 100px;
        height: 100px;
        background-color: pink;
      } 
    </style>
  • 方案4 javascript

    javascript
    const parent = document.getElementById("parent")
          outerWidth = parent.clientWidth, // content + padding
          outerHeight = parent.clientHeight
          innerWidth = demo.offsetWidth // content + padding + boder
          innerHeight = demo.offsetHeight
    
    demo.style.left = (outerWidth - innerWidth) / 2 + 'px'
    demo.style.top = (outerHeight - innerHeight) / 2 + 'px'