How to Make an Image Fit Perfectly in a Browser Window?

Barbara Streisand
Release: 2024-10-31 07:24:30
Original
684 people have browsed it

How to Make an Image Fit Perfectly in a Browser Window?

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>
Copy after login
<code class="css">* {
    margin: 0;
    padding: 0;
}
.imgbox {
    display: grid;
    height: 100%;
}
.center-fit {
    max-width: 100%;
    max-height: 100vh;
    margin: auto;
}</code>
Copy after login

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>
Copy after login
<code class="javascript">function set_body_height() {
    $('body').height($(window).height());
}
$(document).ready(function() {
    $(window).bind('resize', set_body_height);
    set_body_height();
});</code>
Copy after login
<code class="css">* {
    padding: 0;
    margin: 0;
}
.fit {
    max-width: 100%;
    max-height: 100%;
}
.center {
    display: block;
    margin: auto;
}</code>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!