您好,登錄后才能下訂單哦!
這篇文章主要介紹了css設(shè)置垂直居中的幾種方法,具有一定借鑒價(jià)值,需要的朋友可以參考下。下面就和我一起來看看吧。
1、使用line-height屬性讓文字垂直居中;2、使用CSS3 flex布局讓文字垂直居中;3、使用絕對(duì)定位和transform讓塊狀元素垂直居中;4、使用flex布局讓塊狀元素垂直居中。
css設(shè)置文本文字垂直居中
1、line-height 使文字垂直居中
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>css 垂直居中</title> <style> .box{ width: 300px; height: 300px; background: paleturquoise; line-height:300px; } </style> </head> <body> <div class="box">css 垂直居中了--文本文字</div> </body> </html>
效果圖:
這樣就能讓div中的文字水平垂直居中了
2、CSS3的flex布局 使文字垂直居中
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>css 垂直居中</title> <style> .box{ width: 300px; height: 200px; background: paleturquoise; /*設(shè)置為伸縮容器*/ display: -webkit-box; display: -moz-box; display: -ms-flexbox; display: -webkit-flex; display: flex; /*垂直居中*/ -webkit-box-align: center;/*舊版本*/ -moz-box-align: center;/*舊版本*/ -ms-flex-align: center;/*混合版本*/ -webkit-align-items: center;/*新版本*/ align-items: center;/*新版本*/ } </style> </head> <body> <div class="box">css 垂直居中--文本文字(彈性布局)</div> </body> </html>
效果圖:
css設(shè)置塊狀元素垂直居中
1、使用絕對(duì)定位和transform(未知元素高度)
如果我們不知道元素的高度,那么就需要先將元素定位到容器的中心位置,然后使用 transform 的 translate 屬性,將元素的中心和父容器的中心重合,從而實(shí)現(xiàn)垂直居中:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>css 垂直居中</title> <style> .box{ width: 300px; height: 300px; background: #ddd; position: relative; } .child{ background: #93BC49; position: absolute; top: 50%; transform: translate(0, -50%); } </style> </head> <body> <div class="box"> <div class="child">css 垂直居中,css 垂直居中,css 垂直居中,css 垂直居中,css 垂直居中</div> </div> </body> </html>
效果圖:
2、使用flex布局
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>css 垂直居中</title> <style> .box{ width: 300px; height: 300px; background: #ddd; display: flex; flex-direction: column; justify-content: center; } .child{ width: 300px; height: 100px; background: #08BC67; line-height: 100px; } </style> </head> <body> <div class="box"> <div class="child">css 垂直居中了--彈性布局</div> </div> </body> </html>
效果圖:
以上就是css設(shè)置垂直居中的幾種方法的詳細(xì)內(nèi)容了,看完之后是否有所收獲呢?如果想了解更多相關(guān)內(nèi)容,歡迎來億速云行業(yè)資訊!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。