盒子居中的几种方式

几种盒子居中方式

.father代表父盒子,.child代表子盒子

  • 方式一
    .father
    {
      position: relative;
      width: 500px;
      height: 500px;
      background-color: pink;
    }
    .child
    {
      position: absolute;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
      width: 300px;
      height: 300px;
      margin: auto;
      background-color: #333;
    }
    
  • 方式二

    .father
    {
      display: flex;
      width: 500px;
      height: 500px;
      background-color: pink;
    }
    .child
    {
      width: 300px;
      height: 300px;
      margin: auto;
      background-color: #333;
    }
    
  • 方式三

    .father
    {
      position: relative;
      width: 500px;
      height: 500px;
      background-color: pink;
    }
    .child
    {
      position: absolute;
      top: 50%;
      left: 50%;
      width: 300px;
      height: 300px;
      margin: -150px 0 0 -150px;
      background-color: #333;
    }
    
  • 方式四

    .father
    {
      position: relative;
      width: 500px;
      height: 500px;
      background-color: pink;
    }
    .child
    {
      position: absolute;
      top: 50%;
      left: 50%;
      width: 300px;
      height: 300px;
      transform: translate(-50%,-50%);
      background-color: #333;
    }
    
  • 方式五

    .father
    {
      width: 500px;
      height: 500px;
      text-align: center;
      background-color: pink;
    }
    .father:after
    {
      display: inline-block;
      height: 100%;
      content: '';
      vertical-align: middle;
    }
    .child
    {
      display: inline-block;
      width: 300px;
      height: 300px;
      vertical-align: middle;
      background-color: #333;
    }
    
  • 方式六

    .father
    {
      display: flex;
      width: 500px;
      height: 500px;
      background-color: pink;
      justify-content: center;
      align-items: center;
    }
    .child
    {
      display: table-cell;
      width: 300px;
      height: 300px;
      background-color: #333;
    }
    
  • 方式七 (内容写在child盒子中)

    .father
    {
      display: table;
      width: 500px;
      height: 500px;
      background-color: pink;
    }
    .child
    {
      display: table-cell;
      width: 300px;
      height: 300px;
      text-align: center;
      vertical-align: middle;
    }
    
赞 赏
微信扫一扫