CSS各类居中

63 阅读1分钟

1.使用定位实现居中

已知元素宽高


<style>
    div{
        width: 300px;
        height: 300px;
        background: pink;
        position: fixed;
        left:50%;
        top:50%;
        margin-left:-150px;
        margin-top:-150px;
    }
</style>

未知元素宽高

    div{
        width: 300px;
        height: 300px;
        background: pink;
        position: fixed;
              top: 0;right: 0;bottom: 0;left: 0;
              margin: auto 
    }

2.弹性布局

<style>
.parent {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>

3.利用 transform

  <style>
    .parent {
      width: 500px;
      height: 500px;
      border: 1px solid #000;
      position: relative;
    }

    .child {
      width: 100px;
      height: 100px;
      border: 1px solid #999;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
  </style>
</head>

<body>
  <div class="parent">
    <div class="child">子元素</div>
  </div>
</body>

4.grid布局

.parent {
  display: grid;
  place-items: center;
}