# DAY5 - 版型置中開發 / margin 0 auto - 使物件自適應其網頁瀏覽器的寬度,取一個置中的位置。 ``` .box { background-color: blue; width: 150px; height: 150px; margin-left: auto; margin-right: auto; } ``` ![](https://i.imgur.com/Tx16lzU.png) - 原理如下圖: box 根據當下 body 的寬度,自適應推擠左右同比例的間距。 ![](https://i.imgur.com/xrxB8Fk.png) ### 容器內製作一個小元素,header 概念: - 假設 box 是一個容器,裡面開發一個新的 header,也自動產生左右等比例間距置中,怎麼寫? ``` // HTML <div class="box"> <div class="header"></div> </div> ``` ``` // CSS .box { background-color: blue; width: 150px; height: 150px; margin-left: auto; margin-right: auto; } .header { width: 30px; height: 30px; background-color: darkturquoise; margin-left: auto; margin-right: auto; } ``` ![](https://i.imgur.com/mHm8grA.png) - 其水平置中的做法,也參考當前**元素與父層的關係**。 header 會自適應 box 當前的範圍,透過 margin auto 來去尋找等比例的距離。 ### 常見的排版: - header - 表頭 - content - 中間的內容 - footer - 表尾 - 不需要額外寫寬度,內元素會自動適應容器(container)而產生寬度。 ``` <div class="container"> <div class="header"></div> <div class="content"></div> <div class="footer"></div> </div> ``` ``` .container { width: 800px; margin-left: auto; margin-right: auto; } .header { height: 100px; background: blue; } .content { height: 300px; background-color: aquamarine; } .footer { height: 150px; background-color: burlywood; } ``` ![](https://i.imgur.com/9TgPSLv.png) ### content 不建議寫死高度。 - 主因是,content,通常是網站主內容顯示的區塊,很有可能會時常做更新,會建議用元素自適應推擠高度+padding 的做法。 ###### tags: `Re:0 前端工程師之路 - HTML CSS 篇章`