宽度拉伸:把width设置成100%,height设置auto
高度拉伸:把height设置成100%,width设置auto
<!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>图片自适应</title> <style> div { width: 500px; height: 300px; border: 1px solid black; /* 使得图片居中对齐 */ text-align: center; margin: 20px auto; /* 使得图片居中对齐 */ /* display: flex; align-items: center; justify-content: center; */ } img { /* flex: 1; */ /* width: 100%; height: auto; */ /* margin: 0 auto; */ width: auto; height: 100%; } </style> </head> <body> <div> <img src="01.jpg" alt=""> </div> <div> <img src="02.jpeg" alt=""> </div> </body> </html>
效果如下:
此例子是宽度自适应,如果是高度自适应互换宽和高即可