margin:auto你真的理解么?


含義

margin:auto是具有強烈計算意味的關鍵字,用來計算元素對應方向應該獲得的剩余空間大小

填充規則

(1) 如果一側定值,一側auto,則auto為剩余空間大小
(2) 如果兩側均是auto,則平分剩余空間

<style>
    .father {
      width: 300px;
      background-color: #f0f3f9;
    }
    .son {
      width: 200px;
      height: 120px;
      margin-right: 80px;
      margin-left: auto;
      background-color: #cd0000;
    }
  </style>

<div class="father">
    <div class="son"></div>
  </div>


左邊距是20px,右邊距是80px。這里son寬度是200px,容器是300px,總剩余空間大小是100px,其中margin-right使用了80px,那么margin-left的‘auto’計算值就是剩余的20px了

margin-left:auto代替float:right實現右對齊

.father {
      width: 300px;
      background-color: #f0f3f9;
    }
    .son {
      width: 200px;
      height: 120px;
      margin-left: auto;
      background-color: #cd0000;
    }

<div class="father">
    <div class="son"></div>
  </div>

magin:atuo配合絕對定位實現水平和垂直方向居中

.father {
      width: 300px;
      height: 150px;
      background-color: #f0f3f9;
      position: relative;
    }

    .son {
      position: absolute;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
      width: 200px;
      height: 100px;
      background-color: #cd0000;
      margin: auto;
    }


<div class="father">
    <div class="son"></div>
  </div>

參考書籍:
《CSS世界》


免責聲明!

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



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