How to Resize an Image to Perfectly Fit the Browser Window
Ensuring an image fits seamlessly within a browser window can present challenges, especially with unknown browser dimensions and image proportions. However, achieving this resizing functionality is possible with a well-crafted approach.
CSS-Only Solution (Updated April 2018)
For browsers supporting modern CSS, a purely CSS solution can be implemented as follows:
<code class="html"><div class="imgbox"> <img class="center-fit" src="pic.png"> </div></code>
<code class="css">* { margin: 0; padding: 0; } .imgbox { display: grid; height: 100%; } .center-fit { max-width: 100%; max-height: 100vh; margin: auto; }</code>
This solution uses CSS grid and dynamically resizes and centers the image within the browser window.
jQuery Solution
Another approach utilizes jQuery to set the body height equal to the window height, allowing the image's max-height property to function as expected:
<code class="html"><img class="center fit" src="pic.jpg"></code>
<code class="javascript">function set_body_height() { $('body').height($(window).height()); } $(document).ready(function() { $(window).bind('resize', set_body_height); set_body_height(); });</code>
<code class="css">* { padding: 0; margin: 0; } .fit { max-width: 100%; max-height: 100%; } .center { display: block; margin: auto; }</code>
This solution involves setting the body height to match the window height, allowing the image to dynamically resize as the window dimensions change.
The above is the detailed content of How to Make an Image Fit Perfectly in a Browser Window?. For more information, please follow other related articles on the PHP Chinese website!