經過css的object-fit: cover;
屬性來裁剪圖片。
屬性參考:
object-fit
效果以下:
CSS控制圖片不變形
完整的網頁代碼以下:css
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8"> <title>CSS控制圖片不變形</title> </head> <body> <div class="w1"> <h3>500PX</h3> <img src="https://n.getimg.net/file/demo/png.png"> </div> <div class="w2"> <h3>700PX</h3> <img src="https://n.getimg.net/file/demo/png.png"> </div> <div class="w3"> <h3>900PX</h3> <img src="https://n.getimg.net/file/demo/png.png"> </div> <style> .w1{ border: 1px solid red; } .w1 img{ height: auto; width: 500px; object-fit: cover; } .w2{ border: 1px solid blue; } .w2 img{ height: auto; width: 700px; object-fit: cover; } .w3{ border: 1px solid pink; } .w3 img{ height: auto; width: 900px; object-fit: cover; } </style> </body> </html>