Html 如何调整图像大小以适合浏览器窗口?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6169666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 08:49:07  来源:igfitidea点击:

How to resize an image to fit in the browser window?

htmlcss

提问by sebnukem

This seems trivial but after all the research and coding I can't get it to work. Conditions are:

这似乎微不足道,但经过所有的研究和编码,我无法让它发挥作用。条件是:

  1. The browser window size is unknown. So please don't propose a solution involving absolute pixel sizes.
  2. The image's original dimensions are unknown, and may or may not already fit the browser window.
  3. The image is vertically and horizontally centered.
  4. The image proportions must be conserved.
  5. The image must be displayed in its entirety in the window (no cropping.)
  6. I do not wish scrollbars to appear (and they shouldn't if the image fits.)
  7. The image automatically resizes when the window dimensions change, to occupy all the available space without being larger than its original size.
  1. 浏览器窗口大小未知。所以请不要提出涉及绝对像素大小的解决方案。
  2. 图像的原始尺寸未知,可能适合也可能不适合浏览器窗口。
  3. 图像垂直和水平居中。
  4. 图像比例必须保持不变。
  5. 图像必须完整显示在窗口中(无裁剪。)
  6. 我不希望出现滚动条(如果图像合适,它们不应该出现。)
  7. 当窗口尺寸改变时,图像会自动调整大小,以占用所有可用空间而不大于其原始大小。

Basically what I want is this:

基本上我想要的是这个:

.fit {
  max-width: 99%;
  max-height: 99%;
}
<img class="fit" src="pic.png">

The problem with the code above is that it doesn't work: the pic takes all the vertical space it needs by adding a vertical scroll bar.

上面代码的问题在于它不起作用:图片通过添加垂直滚动条来占用它需要的所有垂直空间。

At my disposal is PHP, Javascript, JQuery but I'd kill for a CSS-only solution. I don't care if it doesn't work in IE.

我可以使用 PHP、Javascript、JQuery,但我会为仅使用 CSS 的解决方案而死。我不在乎它是否在 IE 中不起作用。

回答by sebnukem

Update 2018-04-11

更新 2018-04-11

Here's a Javascript-less, CSS-onlysolution. The image will dynamically be centered and resized to fit the window.

这是一个无 Javascript,仅 CSS 的解决方案。图像将动态居中并调整大小以适合窗口。

<html>
<head>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        .imgbox {
            display: grid;
            height: 100%;
        }
        .center-fit {
            max-width: 100%;
            max-height: 100vh;
            margin: auto;
        }
    </style>
</head>
<body>
<div class="imgbox">
    <img class="center-fit" src='pic.png'>
</div>
</body>
</html>


The [other, old] solution, using JQuery, sets the height of the image container (bodyin the example below) so that the max-heightproperty on the image works as expected. The image will also automatically resize when the client window is resized.

[other, old] 解决方案使用 JQuery 设置图像容器的高度(body在下面的示例中),以便max-height图像上的属性按预期工作。调整客户端窗口大小时,图像也会自动调整大小。

<!DOCTYPE html>
<html>
<head>
    <style>
        * {
            padding: 0;
            margin: 0;
        }
        .fit { /* set relative picture size */
            max-width: 100%;
            max-height: 100%;
        }
        .center {
            display: block;
            margin: auto;
        }
    </style>
</head>
<body>

<img class="center fit" src="pic.jpg" >

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" language="JavaScript">
    function set_body_height() { // set body height = window height
        $('body').height($(window).height());
    }
    $(document).ready(function() {
        $(window).bind('resize', set_body_height);
        set_body_height();
    });
</script>

</body>
</html>

Note: User gutierrezalex packaged a very similar solution as a JQuery plugin on this page.

注意:用户gutierrezalex 在此页面上打包了一个与JQuery 插件非常相似的解决方案。

回答by Neolisk

Here is a simple CSS only solution (JSFiddle), works everywhere, mobile and IE included:

这是一个简单的CSS 解决方案(JSFiddle),适用于任何地方,包括移动和 IE:

CSS 2.0:

CSS 2.0:

html, body {
    height: 100%;
    margin: 0;
    padding: 0;
}

img {
    padding: 0;
    display: block;
    margin: 0 auto;
    max-height: 100%;
    max-width: 100%;
}

HTML:

HTML:

<body>
  <img src="images/your-image.png" />
</body>

回答by Max

CSS3 introduces new units that are measured relative to the viewport, which is the window in this case. These are vhand vw, which measure viewport height and width, respectively. Here is a simple CSS only solution:

CSS3 引入了相对于视口(在本例中为窗口)测量的新单位。它们是vhvw,分别测量视口的高度和宽度。这是一个简单的仅 CSS 解决方案:

img {
    max-width: 100%;
    max-height: 100vh;
    height: auto;
}

The one caveat to this is that it only works if there are no other elements contributing height on the page.

对此的一个警告是,它仅在页面上没有其他元素贡献高度时才有效。

回答by Mark E. Haase

If you are willing to put a container element around your image, a pure CSS solution is simple. You see, 99% height has no meaning when the parent element will extend vertically to contain its children. The parent needs to have a fixed height, say... the height of the viewport.

如果您愿意在图像周围放置一个容器元素,纯 CSS 解决方案很简单。您会看到,当父元素将垂直扩展以包含其子元素时,99% 的高度没有意义。父级需要有一个固定的高度,比如……视口的高度。

HTML

HTML

<!-- use a tall image to illustrate the problem -->
<div class='fill-screen'>
    <img class='make-it-fit' 
         src='https://upload.wikimedia.org/wikipedia/commons/f/f2/Leaning_Tower_of_Pisa.jpg'>
</div>

CSS

CSS

div.fill-screen {
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    text-align: center;
}

img.make-it-fit {
    max-width: 99%;
    max-height: 99%;
}

Play with the fiddle.

小提琴

回答by am0wa

Resize Image to Fit the Screen by the Longest Side maintaining its Aspect Ratio

调整图像大小以适应屏幕的最长边保持其纵横比

img[src$="#fit"] {
    width: 100vw;
    height: auto;
    max-width: none;
    max-height: 100vh;
    object-fit: contain;
}
  • width: 100vw- image width will be 100% of view port
  • height: auto- image height will be scaled proportionally
  • max-height: 100vw- if image height would become more than view port it will be decreased to fit the screen, consequently image width will be decreased because of the following property

  • object-fit: contain- the replaced content is scaled to maintain its aspect ratio while fitting within the element's content box

    Note: object-fitis fully supported only since IE 16.0

  • width: 100vw- 图像宽度将为视口的 100%
  • height: auto- 图像高度将按比例缩放
  • max-height: 100vw- 如果图像高度将超过视口,它将减小以适应屏幕,因此由于以下属性,图像宽度将减小

  • object-fit: contain- 替换的内容被缩放以保持其纵横比,同时适合元素的内容框

    注意:object-fit仅自 IE 16.0 起完全支持

回答by usrrname

My general lazy CSS rule:

我一般的懒惰 CSS 规则:

.background{
width:100%;
height:auto;
background: url('yoururl.jpg') no-repeat center;
background-position: 50% 50%;
background-size: 100% cover!important;
overflow:hidden;
}

This may zoom in on your image if it is low-res to begin with (that's to do with your image quality and size in dimensions. To center your image, you may also try (in the CSS)

如果一开始是低分辨率的,这可能会放大您的图像(这与您的图像质量和尺寸大小有关。要使图像居中,您也可以尝试(在 CSS 中)

display:block;    
margin: auto 0; 

to center your image

将您的图像居中

in your HTML:

在您的 HTML 中:

<div class="background"></div>

回答by Rohit Vipin Mathews

I had a similar requirement, and had to do it it basic CSS and JavaScript. No JQuery available.

我有一个类似的要求,并且必须使用基本的 CSS 和 JavaScript。没有可用的 JQuery。

This is what I got working.

这就是我的工作。

<html>
      <head>
            <style>
                   img {
                          max-width: 95% !important;
                          max-height: 95% !important;
                       }
            </style>
            <script>
                   function FitImagesToScreen() {
                      var images = document.getElementsByTagName('img');
                      if(images.length > 0){
                         for(var i=0; i < images.length; i++){
                             if(images[i].width >= (window.innerWidth - 10)){
                                 images[i].style.width = 'auto';
                               }
                            }
                         }
                   }
             </script>
      </head>
      <body onload='FitImagesToScreen()'>
      ----    
      </body>
</html>

Note :I haven't used 100% for image width as there was always a bit of padding to be considered.

注意:我没有使用 100% 的图像宽度,因为总是需要考虑一些填充。

回答by Hassan Siddiqui

Make it simple. Thanks

让它变得简单。谢谢

.bg {
  background-image: url('https://images.unsplash.com/photo-1476820865390-c52aeebb9891?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80');
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
  height: 100vh;
  width: 100vw;
}
<div class="bg"></div>

回答by TomC

I know there's already a few answers here, but here is what I used:

我知道这里已经有一些答案,但这是我使用的:

max-width: 100%;
max-height: 100vh;
width: auto;
margin: auto;

回答by RobinJ

width: 100%;
overflow: hidden;

I believe that should do the trick.

我相信这应该可以解决问题。