css之auto值的含義

1.水平方向的auto值

htmlcss

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

 

常規流塊盒的總寬度,等於其包含塊的寬度,也就是其父元素的內容區域html

不設置width,width的默認值爲auto,表示吸取掉塊盒的剩餘空間spa

css3d

    .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; */
    }

顯示效果code

 

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

 

 

 

 

 

 

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

 

 

 

margin的默認值爲0,值爲auto也是吸取掉剩餘空間的意思class

但若是給塊盒同時設置了width和margin,width的優先級更高im

 

若設置了width,且width border padding margin計算事後 仍然有剩餘空間 因爲塊盒總寬度須要等於其包含塊的寬度  因此該剩餘空間默認狀況下會被margin-right所有吸取margin

css

    .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;
    }

 

 

 

 

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

css

    .father .child {
      border: 5px solid red;
      height: 100px;
      background: lightcoral;
      /* 不設置width等同於width爲auto */
      width: 100px;
      /* 設置margin-left爲auto,吸取剩餘空間 */
      margin-left: 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;
    }

 

 

2.垂直方向的auto值

height: auto 適應內容的寬度

margin: auto 表示0

相關文章
相關標籤/搜索