css使子元素在父元素居中的各種方法


html結構:

<div class="parent">
  <div class="child"></div>
</div>

方法一: display:flex

  .parent {
    width: 500px;
    height: 500px;
    background: red;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .child {
    width: 100px;
    height: 100px;
    background: blue;
  }

方法二:display:table-cel

  .parent{
    width: 500px;
    height: 500px;
    background: red;
    display: table-cell;
    vertical-align: middle;
  }
  .child{
    width: 100px;
    height: 100px;
    background: blue;
    margin: auto;
  }

方法三:絕對定位和0

  .parent{
    width: 500px;
    height: 500px;
    background: red;
    position: relative;
  }
  .child{
    width: 100px;
    height: 100px;
    background: blue;
    margin: auto;
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;    
  }

方法四:負邊距

  .parent{
    width: 500px;
    height: 500px;
    background: red;
    position: relative;
  }
  .child{
    width: 100px;
    height: 100px;
    background: blue;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: -50px;
    margin-top: -50px;  
  }

以上四種方法都可以完成用css實現子元素在父元素實現水平和垂直居中。

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM