天天看點

css之auto值的含義

1.水準方向的auto值

html

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

正常流塊盒的總寬度,等于其包含塊的寬度,也就是其父元素的内容區域

不設定width,width的預設值為auto,表示吸收掉塊盒的剩餘空間

css

.father {
      height: 200px;
      border: 5px solid red;
      padding: 30px;
      background: lightblue;
    }
    .father .child {
      border: 5px solid red;
      height: 100px;
      background: lightcoral;
      /* 不設定width等同于width為auto */
      /* width: auto; */
    }      

顯示效果

css之auto值的含義

此時child塊盒的總寬度為1354px,減去左右border的10px,還剩餘1344px,是以width的具體值為1344px

css之auto值的含義

child的包含塊的寬度,也就是father的content部分,也為1354px

css之auto值的含義

margin的預設值為0,值為auto也是吸收掉剩餘空間的意思

但如果給塊盒同時設定了width和margin,width的優先級更高

若設定了width,且width border padding margin計算過後 仍然有剩餘空間 由于塊盒總寬度需要等于其包含塊的寬度  是以該剩餘空間預設情況下會被margin-right全部吸收

.father {
      height: 200px;
      border: 5px solid red;
      padding: 30px;
      background: lightblue;
    }
    .father .child {
      border: 5px solid red;
      height: 100px;
      background: lightcoral;
      /* 設定width為100px */
      width: 100px;
    }      
css之auto值的含義

若設定margin-left:auto; 就表示剩餘空間全被margin-left吸收 塊盒就排列到包含塊的最右邊了

.father .child {
      border: 5px solid red;
      height: 100px;
      background: lightcoral;
      /* 不設定width等同于width為auto */
      width: 100px;
      /* 設定margin-left為auto,吸收剩餘空間 */
      margin-left: auto;
    }      
css之auto值的含義

是以我們經常使用的正常流塊盒width固定,設定margin: auto; 就表示左右margin平均吸收掉剩餘空間  是以就能實作水準居中了

 css

.father .child {
      border: 5px solid red;
      height: 100px;
      background: lightcoral;
      /* 不設定width等同于width為auto */
      width: 100px;
      /* 設定margin左右都為auto,兩邊平均吸收剩餘空間 */
      margin: auto;
    }      
css之auto值的含義

2.垂直方向的auto值