【css】一行或者多行垂直水平居中
阿新 • • 發佈:2018-11-23
1.方法一:使用css3彈性盒子(相容IE10及以上瀏覽器,firefox,chrome,safari 5.1.7不支援)
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>菜鳥教程(runoob.com)</title> <style> #main { display: flex; display:-webkit-flex; flex-direction:column;/*縱向排列*/ } #main div{ width: 40px; height: 40px; display: flex; display:-webkit-flex; justify-content: center;/*水平居中*/ align-items: center;/*垂直居中*/ -webkit-align-items:center; } /*或者 #main div { width: 40px; height: 40px; display: flex; justify-content: space-around; flex-direction: column; align-items: center }*/ </style> </head> <body> <div id="main"> <div style="background-color:coral;">A</div> <div style="background-color:lightblue;">B</div> <div style="background-color:khaki;">C</div> <div style="background-color:pink;">D</div> <div style="background-color:lightgrey;">E</div> <div style="background-color:lightgreen;">F</div> </div> </body> </html>
效果:
2.使用display:table-cell(不確定高度的容器中垂直居中)
ps:W3C上對vertical-align的定義:vertical-align 屬性設定元素的垂直對齊方式。
該屬性定義行內元素的基線相對於該元素所在行的基線的垂直對齊。允許指定負長度值和百分比值。這會使元素降低而不是升高。
在表單元格中,這個屬性會設定單元格框中的單元格內容的對齊方式。
display:table-cell;
vertical-align:middle;
text-align:center;
相容性:IE8及以上瀏覽器,chrome,firefox
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>相容ie8及以上瀏覽器</title> <style type="text/css"> .box{ width:300px; height:300px; border:1px solid red; display:table-cell; vertical-align:middle; text-align:center; } .align-center-vertical{ } </style> </head> <body> <div class="box"> <div class="align-center-vertical"> 3問無為謂我我我我問問3問無為謂我我我我問問3問無為謂我我我我問問3問無為謂我我我我問問3問無為謂我我我我問問3問無為謂我我我我問問</div> </div> </body> </html>
效果:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>相容ie8及以上瀏覽器</title> <style type="text/css"> .box { border: 1px dashed #cccccc; height: 300px; width:500px; font-size:0; } .box p, .box i { display: inline-block; vertical-align: middle; overflow: hidden; *display:inline; *zoom:1; } .box i { height: 100%; width: 0; } .box p { font-size: 14px; width: 100%; } </style> </head> <body> <div class="box"> <p class="text">多行文字的垂直居中多行文字的垂直居中多行文字的垂直居中多行文字的垂直居中多行文字的垂直居中多行文字的垂直居中多行文字的垂直居中多行文字的垂直居中多行文字的垂直居中多行文字的垂直居中多行文字的垂直居中多行文字的垂直居</p> <i></i> </div> </body> </html>
3.負margin的寫法(已知固定寬高)
絕對定位 position :absolute;
top:50%; left: 50%;
margin-top:-高度的一般;
margin-left:-寬度的一半
4.絕對定位+transform(transform在IE9及其以下是不支援的)
.center {
left: 50%;
top: 50%;
position: absolute;
-webkit-transform: translate3D(-50%,-50%,0);
-ms-transform: translate3D(-50%,-50%,0);
-moz-transform: translate3D(-50%,-50%,0);
-o-transform: translate3D(-50%,-50%,0);
transform: translate3D(-50%,-50%,0);
z-index: 100;
}