css實現(xiàn)盒子內(nèi)部 div水平垂直居中

總結(jié)一下利用css實現(xiàn)盒子內(nèi)部 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減去寬高的一半
局限性:需要知道需要垂直居中的寬高才能實現(xiàn)

  <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
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容