How Can I Resize an Image to Fit the Browser Window Without Distortion?

Barbara Streisand
Release: 2024-11-01 15:51:55
Original
990 people have browsed it

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>
Copy after login

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>
Copy after login

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!

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!