--- tags: CSS - 練習 --- # CSS 水平垂直置中 題目: > https://codepen.io/wuguohua0529/pen/poaNmeG ## 文字置中  ### line-height ``` // html <div class="div1">文字置中1</div> // css .div1 { background-color: #FCD000; width: 200px; height: 200px; } ``` <!-- // 將文字置中,並使將行高設置跟高度一樣 text-align: center; line-height: 200px; --> ### flex ``` // html <div class="div2">文字置中2</div> // css .div2 { background-color: #80a6d9; width: 200px; height: 200px; } ``` <!-- // 用flex排版,並將水平與垂直設定置中 display: flex; justify-content: center; align-items: center; --> ## 區塊置中  ### margin ``` // html <div class="div3">div3</div> // css .div3 { background-color: #80d98d; width: 200px; height: 200px; } ``` <!-- // 用text-align、line-height將內容置中,margin將區塊置中 text-align: center; line-height: 200px; margin: auto; -->  ### absolute + margin 負值 ``` // html <div class="div4-box"> <div class="div4">div4</div> </div> // css .div4-box { width: 500px; height: 250px; border: 1px solid #f00; } .div4 { width: 200px; height: 200px; background: #ccc; } ``` <!-- //透過margin將父元素置中,並設定相對位置 margin: auto; position: relative; //透過absolute將子元素置中 position: absolute; top:50%; left: 50%; margin-left: -100px; margin-top: -100px; --> ### absolute + margin auto ``` // html <div class="div5-box"> <div class="div5">div5</div> </div> // css .div5-box { width: 500px; height: 250px; border: 1px solid #f00; } .div5 { width: 200px; height: 200px; background: #ccc; } ``` <!-- //透過margin將父元素置中,並設定相對位置 margin: auto; position: relative; //透過absolute將子元素置中 position: absolute; top: 0; right: 0; bottom: 0; left: 0; margin: auto; --> ### flex ``` // html <div class="div6-box"> <div class="div6">div6</div> </div> // css .div6-box { width: 500px; height: 250px; border: 1px solid #f00; } .div6 { width: 200px; height: 200px; background: #ccc; } ``` <!-- // 用flex排版,並將水平與垂直設定置中 display: flex; justify-content: center; align-items: center; margin: auto; --> ### 偽元素 ::before ``` // html <div class="div7-box"></div> // css .div7-box { width: 500px; height: 250px; border: 1px solid #f00; } .div7-box::before { width: 200px; height: 200px; background: #ccc; } ``` <!-- // 透過margin將父元素置中,用flex排版,並將水平與垂直設定置中 margin: auto; display: flex; justify-content: center; align-items: center; --> <!-- //設定內容,否則不會出現 content: "div7"; --> 答案: > https://codepen.io/wuguohua0529/pen/RwQgLyP
×
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