1.单行文字居中
2.多行文字居中
3.利用background-position:center;的图片居中
4.利用display:table-cell;属性的图片居中
1 <!DOCTYPE html> 2 <html> 3 4 <head> 5 <meta charset="utf-8"> 6 <meta http-equiv="X-UA-Compatible" content="IE=edge"> 7 <title>display:table-cell;垂直居中</title> 8 <meta name="viewport" content="width=device-width, initial-scale=1"> 9 <style> 10 .pic-box { 11 display: table-cell ; 12 background: pink; 13 font-size: 0 ; 14 text-align: center; 15 height: 600px; 16 width: 600px; 17 vertical-align: middle ; 18 } 19 20 img{ 21 display: inline-block ; 22 } 23 24 </style> 25 </head> 26 27 <body> 28 <div class="pic-box"> 29 <img src="https://img.alicdn.com/bao/uploaded/i1/742862115/O1CN01yjhiHd1RUiBD5i23h_!!742862115.jpg_300x300.jpg"> 30 </div> 31 </body> 32 33 </html>
5.利用display:inline-block;属性的图片居中
6.利用position:absolute;属性的居中
示例代码
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <meta http-equiv="X-UA-Compatible" content="ie=edge"> 7 <title>absolute居中</title> 8 <style> 9 .container-box{ 10 background: green ; 11 position: relative; 12 width: 600px ; 13 height: 800px ; 14 } 15 .container-seed{ 16 background: pink ; 17 height: 200px ; 18 width: 200px ; 19 position: absolute ; 20 /* 21 先将距离顶部和左边的距离都设置成50% 22 再减去需要居中容器本身的一半值居中 即下方的margin 负值回去 23 */ 24 top: 50% ; 25 left: 50% ; 26 margin: -100px 0 0 -100px; 27 } 28 </style> 29 </head> 30 <body> 31 <!-- 例如容器居中 --> 32 <h1>该方法适合已知需要居中元素的大小/若不确定则需要JS辅助</h1> 33 <div class="container-box"> 34 <div class="container-seed">test</div> 35 </div> 36 </body> 37 </html>
7.利用:after 伪类 + content 使无法确定大小图片居中
示例代码
1 <!DOCTYPE html> 2 <html> 3 4 <head> 5 <meta charset="utf-8"> 6 <meta http-equiv="X-UA-Compatible" content="IE=edge"> 7 <title>垂直居中</title> 8 <meta name="viewport" content="width=device-width, initial-scale=1"> 9 <style> 10 .pic-box { 11 background: pink; 12 font-size: 0 ; 13 text-align: center; 14 height: 600px; 15 width: 600px; 16 } 17 18 img{ 19 display: inline-block ; 20 vertical-align: middle ; 21 } 22 23 .pic-box:before{ 24 display: inline-block ; 25 content: '' ; 26 overflow: hidden; 27 vertical-align: middle ; 28 height: 100%; 29 width: 0 ; 30 } 31 32 </style> 33 </head> 34 35 <body> 36 <div class="pic-box"> 37 <img src="https://img.alicdn.com/bao/uploaded/i1/742862115/O1CN01yjhiHd1RUiBD5i23h_!!742862115.jpg_300x300.jpg"> 38 </div> 39 </body> 40 41 </html>