css实现盒子内部 div水平垂直居中

版权声明:未经允许不得转载 https://blog.csdn.net/pinbolei/article/details/84105893

总结一下利用css实现盒子内部 div居中的几种方法


1.水平居中

1)margin: 0 auto

  <style>
    .box {
      width: 300px;
      height: 300px;
      border: 2px solid black;
    }
    .box1 {
      width: 100px;
      height: 100px;
      background: red;
      margin:0 auto;
    }
  </style>
<body>
  <div class="box">
    <div class="box1"></div>
  </div>
</body>

1-1

2.水平垂直居中

1)定位和需要定位的元素的margin减去宽高的一半
局限性:需要知道需要垂直居中的宽高才能实现

  <style>
    .box {
      width: 300px;
      height: 300px;
      border: 2px solid black;
      position:relative;
    }

    .box1 {
      width: 100px;
      height: 100px;
      background: red;
      position:absolute;
      top:50%;
      left:50%;
      margin-top: -50px;
      margin-left: -50px;
    }
  </style>
<body>
  <div class="box">
    <div class="box1"></div>
  </div>
</body>

2-1
2)position定位和margin:auto;
不受宽高限制

  <style>
    .box {
      width: 300px;
      height: 300px;
      border: 2px solid black;
      position:relative;
    }

    .box1 {
      width: 100px;
      height: 100px;
      background: red;
      position:absolute;
      left:0;
      top:0;
      right:0;
      bottom:0;
      margin:auto;
    }
  </style>
<body>
  <div class="box">
    <div class="box1"></div>
  </div>
</body>

2-2
3)定位和transfrom

  <style>
    .box {
      width: 300px;
      height: 300px;
      border: 2px solid black;
      position:relative;
    }

    .box1 {
      width: 100px;
      height: 100px;
      background: red;
      position:absolute;
      left:50%;
      top:50%;
      transform: translate(-50%,-50%);
    }
  </style>
<body>
  <div class="box">
    <div class="box1"></div>
  </div>
</body>

2-3
4)flex居中

  <style>
    .box {
      width: 300px;
      height: 300px;
      border: 2px solid black;
      display:flex;
      justify-content: center;
      align-items: center;
    }
    
    .box1 {
      width: 100px;
      height: 100px;
      background: red;
    }
  </style>
<body>
  <div class="box">
    <div class="box1"></div>
  </div>
</body>

2-4
5)diplay:table-cell

  <style>
    .box {
      width: 300px;
      height: 300px;
      border: 2px solid black;
      display:table-cell;
      vertical-align: middle;
      text-align: center;
    }

    .box1 {
      width: 100px;
      height: 100px;
      background: red;
      display:inline-block;
    }
  </style>
<body>
  <div class="box">
    <div class="box1"></div>
  </div>
</body>

2-5

猜你喜欢

转载自blog.csdn.net/pinbolei/article/details/84105893