# [Style] CSS 水平垂直置中的方法 ###### tags `前端筆記` `style` <div style="display: flex; justify-content: flex-end"> > created: 2023/11/07 </div> ## HTML 架構 目前有下列的 HTML 架構,請問該怎麼透過 CSS 實作水平垂直置中? ```htmlembedded= <div class="outer"> <div class="inner"></div> </div> ``` ## 使用 `display: flex`, `align-items: center` 及 `justify-content: center` - 容器設定 `display: flex` - 容器設定 `align-items: center`:代表第一層項目會垂直對齊到中間 - 容器設定 `justify-content: center`:代表第一層項目會水平對齊到中間(將容器空白平分置項目的左右兩側) ```css= .outer { width: 500px; height: 500px; display: flex; align-items: center; justify-content: center; background-color: blue; } .inner { width: 180px; height: 180px; background-color: pink; } ``` [CSS 垂直水平置中 - 1 (flex)](https://codepen.io/lun0223/pen/dyaNvxz) ## 使用 `display: flex` 及 `margin: auto` - 容器設定 `display: flex`(重要,讓第一層項目可以脫離一般的 flow) - 項目設定 `margin: auto`:讓瀏覽器自己推算 `.inner` 該離 `.outer` 多遠 ```css= .outer { width: 500px; height: 500px; display: flex; background-color: blue; } .inner { width: 180px; height: 180px; background-color: pink; margin: auto; } ``` [CSS 垂直水平置中 - 2 (margin)](https://codepen.io/lun0223/pen/eYxgWJJ) ## 容器使用 `position: relative` 供項目定位 - 容器設定 `position: relative` 供子項目定位 - 項目設定 `position: absolute`:該標籤會往上層找,直到找到其元素為 `position: relative / absolute`(目標元素),此時該元素就會以目標元素定位(依照 `top`, `right`, `bottom` 及 `left`) - 項目需額外設定 `transform: translate(-50%, -50%);`,因為元素預設是左上角為起點,此時因為起點 = `.outer` 的中心,所以必須再針對起點(也就是項目的左上角移動 `x -50%, y -50%`,讓整個項目再次移動位置) ```css= .outer { width: 500px; height: 500px; position: relative; background-color: blue; } .inner { width: 180px; height: 180px; background-color: pink; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } ```  (`.inner` 的左上角為 `.outer` 的中心)  (再次移動 `.inner` 的位置) [CSS 垂直水平置中 - 3 (position)](https://codepen.io/lun0223/pen/abXpWmJ) ## 使用 `display: grid`, `place-content: center` - 容器設定 `display: grid` 及 `place-content: center`:等價於容器設定 `justify-content: center`(水平線)及 `align-items: center`(垂直線) ```css= .outer { width: 500px; height: 500px; display: grid; background-color: blue; place-content: center; /* 等價於 * justify-content: center; * align-items: center; * */ } .inner { width: 180px; height: 180px; background-color: pink; } ``` [CSS 垂直水平置中 - 4 (grid)](https://codepen.io/lun0223/pen/xxMgdYP)
×
Sign in
Email
Password
Forgot password
or
Sign in via Google
Sign in via Facebook
Sign in via X(Twitter)
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
Continue with a different method
New to HackMD?
Sign up
By signing in, you agree to our
terms of service
.