# flex 使用心得 ###### tags: `CSS` `前端` ## 前言 在練習切版 kata 的時候嘗試使用 flex 進行排版,紀錄一下初步的使用心得。 ## flex 容器觀念 flex 基本用法之前有寫了一篇 **[筆記](https://hackmd.io/1ka3-I7NQ5yDIK_hEfM8Xg)**,屬性的設定一個在容器、另一個則在項目,代表我得很清楚我現在想進行排版的內容,該裝在什麼容器當中。 我可能標題想靠左、內文想置中,這樣的話標題跟內文就無法放在同一個容器當中,例如 ```htmlembedded= <div class="box"> <h2> 標題 </h2> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. </p> </div> ``` ```css .box { display:flex; } h2,p { flex:none; } ``` 我這樣寫,標題跟內文會一起被當成同一階級的項目,會並排在一起  如果想要做到「標題靠左、內文置中」我就得把 h2, p 分別放在不同的容器當中,寫法如下 ```htmlembedded= <div class="box"> <div class="titleBox"> <h2>標題</h2> </div> <div class="textBox"> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. </p> </div> </div> ``` ```css= .textBox { display:flex; justify-content: center; } .textBox>p { flex:none; } ``` [codepen 連結](https://codepen.io/kelen1995/pen/RwLWvGv) 這樣的寫法會多出很多做為容器的 \<div>,但好處就是排版的彈性更高 如果看不慣一大堆 \<div> 的話,或許就要花點時間去學會使用 html5 標籤,讓 html 檔的語意更加好懂 [ HTML5 語意的用途](https://hackmd.io/i7Nz7uUJR5mukGTvbeq11g) 這篇筆記的參考資料得好好研讀
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up