Home > Article > Web Front-end > How Can I Resize an Image to Fit the Browser Window Without Distortion?
Resize an Image to Fit Browser Window without Distortion
Resizing an image to fit a browser window is a common task with seemingly simple solutions. However, adhering to specific requirements, such as preserving proportions and avoiding cropping, can present challenges.
Solution without Scrollbars and Javascript (CSS only)
<code class="html"><html> <head> <style> * { margin: 0; padding: 0; } .imgbox { display: grid; height: 100%; } .center-fit { max-width: 100%; max-height: 100vh; /* vh ensures height matches browser window */ margin: auto; } </style> </head> <body> <div class="imgbox"> <img class="center-fit" src='pic.png'> </div> </body> </html></code>
This solution uses CSS Grid to ensure the image container occupies the full window height. The image is then set to fit horizontally and vertically within that container, preserving its aspect ratio and avoiding the addition of scrollbars.
Solution with JQuery
If Javascript is available, another approach is:
<code class="html"><html> <body> <img class="center fit" src="pic.jpg" > <script src="http://code.jquery.com/jquery-latest.js"></script> <script> function set_body_height() { $('body').height($(window).height()); } $(document).ready(function() { $(window).bind('resize', set_body_height); set_body_height(); }); </script> </body> </html></code>
Here, the body height is set to match the window height, ensuring the max-height property on the image functions correctly. The window resize event is also handled to automatically adjust the body height and image size when the window is resized.
The above is the detailed content of How Can I Resize an Image to Fit the Browser Window Without Distortion?. For more information, please follow other related articles on the PHP Chinese website!