大小不固定的图片和多行文字的垂直水平居中

1.多行文字的垂直居中,关键在于 display:table-cell 属性,请看下面的代码:

View Code
 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
 5 <title>无标题文档</title>
 6 <style type="text/css">
 7 
 8 .box{ border:#003399 2px solid; height:100px; width:500px; display:table-cell; vertical-align: middle; padding: 0 20px; font-size:12px}
 9 
10 </style>
11 
12 
13 </head>
14 
15 <body>
16 <div class="box">
17 我是多行文字!我是多行文字!我是多行文字!我是多行文字!我是多行文字!我是多行文字!我是多行文字!我是多行文字!我是多行文字!我是多行文字!我是多行文字!我是多行文字!我是多行文字!
18 
19 
20 </div>
21 
22 </body>
23 </html>

2.未知高度图片的垂直居中:

方法一:

View Code
 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
 5 <title>无标题文档</title>
 6 <style type="text/css">
 7 
 8 .box{ border:#003399 2px solid; height:100px; width:500px; display:table-cell; vertical-align: middle; padding: 0 20px; font-size:12px}
 9 
10 </style>
11 
12 
13 </head>
14 
15 <body>
16 <div class="box">
17  <img src="images/16.jpg" width="100" height="50" alt="" />
18 
19 </div>
20 
21 </body>
22 </html>

方法二:

View Code
 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
 5 <title>无标题文档</title>
 6 <style type="text/css">
 7 
 8 .box{ border:#003399 2px solid; height:100px; width:500px; vertical-align: middle; padding: 0 20px; font-size:12px}
 9 .box img{ vertical-align:middle}
10 .box span{ display:inline-block; vertical-align:middle; height:100%}
11 
12 </style>
13 
14 
15 </head>
16 
17 <body>
18 <div class="box">
19  <img src="images/16.jpg" width="100" height="50" alt="" /><span></span>
20 
21 </div>
22 
23 </body>
24 </html>

以上为本人自己在工作中遇到总结的方法,如有更好,请多多指点!

原文地址:https://www.cnblogs.com/chaoming/p/3010614.html