<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> div { background-color: red; width: 300px; height: 300px; /*此元素会作为一个表格单元格显示 (类似 <td> 和 <th>)*/ display: table-cell; /*垂直居中 */ vertical-align: middle; /*水平居中*/ text-align: center; } </style> </head> <body> <div> <!--<span>垂直居中</span>--> <img src="../share_icon_sina_weibo.png" width="150" height="100"/> </div> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> div { background-color: red; width: 300px; height: 300px; display: flex; /**/ justify-content: center; /*水平居中*/ align-items: Center; /*垂直居中*/ } </style> </head> <body> <div> <img src="../share_icon_sina_weibo.png" width="150" height="100"/> <!--<span>垂直居中</span>--> </div> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> div { background-color: red; width: 300px; height: 300px; position: relative; } img { position: absolute; width: 150px; height: 100px; /*img左上角移动到html的中心*/ top: 50%; left: 50%; /*img左上角向左上角分别移动自身的一半距离*/ margin-left: -75px; margin-top: -50px; /*text-align: center;*/ } </style> </head> <body> <div> <img src="../share_icon_sina_weibo.png"/> <!--<span>垂直居中</span>--> </div> </body> </html>