<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .box{ width:200px; height: 50px; } .box img{ width:100px; vertical-align: middle; } </style> </head> <body> <div class="box"> <img src="123.jpg" alt=""> 阿牛 </div> </body> </html>
bug :上面代码图片底侧会有一个空白缝隙,原因是行内块元素会和文字的基线对齐。
主要解决方法有两种:
- 给图片添加 vertical - align:middle | top | bottom ;等。(提倡使用的)
- 把图片转换为块级元素 display : block ;
案例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .box{ border: 2px solid red; } </style> </head> <body> <div class="box"> <img src="300.jpg" alt="" style="vertical-align: bottom;"> </div> </body> </html>