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

时间:2022-11-28 21:00:42

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. 浏览器窗口大小未知。所以请不要提出涉及绝对像素大小的解决方案。
  3. The image's original dimensions are unknown, and may or may not already fit the browser window.
  4. 图像的原始尺寸未知,可能已经适合浏览器窗口,也可能不适合。
  5. The image is vertically and horizontally centered.
  6. 图像垂直和水平居中。
  7. The image proportions must be conserved.
  8. 图像的比例必须保持不变。
  9. The image must be displayed in its entirety in the window (no cropping.)
  10. 图像必须完整地显示在窗口(不裁剪)。
  11. I do not wish scrollbars to appear (and they shouldn't if the image fits.)
  12. 我不希望滚动条出现(如果图片合适,它们也不应该出现)。
  13. The image automatically resizes when the window dimensions change, to occupy all the available space without being larger than its original size.
  14. 当窗口尺寸发生变化时,图像会自动调整大小,以占用所有可用的空间,而不会超过原来的大小。

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中是否有效。

9 个解决方案

#1


43  

Update 2018-04-11

更新2018-04-11

Here's a Javascript-less, CSS-only solution. 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 (body in the example below) so that the max-height property on the image works as expected. The image will also automatically resize when the client window is resized.

[另一个旧的]解决方案使用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插件非常相似的解决方案。

#2


31  

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

这里有一个简单的CSS only解决方案(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>

#3


14  

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

CSS3引入了相对于viewport(本例中的窗口)进行测量的新单元。这是vh和vw,分别测量视场高度和宽度。这里有一个简单的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.

需要注意的是,只有在页面上没有其他元素贡献高度时,它才会工作。

#4


11  

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.

玩小提琴。

#5


1  

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>

#6


1  

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
  • 宽度:100vw -图片宽度将为视场端口的100%
  • 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

    最大高度:100vw -如果图像的高度超过了视图端口,它将会被降低以适应屏幕,因此由于以下属性,图像的宽度将会降低

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

    对象拟合:包含——被替换的内容被缩放以保持其纵横比,同时在元素的内容框中进行拟合

    Note: object-fit is fully supported only since IE 16.0

    注意:对象匹配只有在ie16.0之后才被完全支持

#7


0  

width: 100%;
overflow: hidden;

I believe that should do the trick.

我相信这是有道理的。

#8


0  

html, body{width: 99%; height: 99%; overflow: hidden}
img.fit{width: 100%; height: 100%;}

Or maybe check this out: http://css-tricks.com/how-to-resizeable-background-image/

或者看看这个:http://css- phs.com/how to resizeable- backgroundimage/

#9


0  

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(int 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%的图像宽度,因为总是需要考虑一些填充。

#1


43  

Update 2018-04-11

更新2018-04-11

Here's a Javascript-less, CSS-only solution. 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 (body in the example below) so that the max-height property on the image works as expected. The image will also automatically resize when the client window is resized.

[另一个旧的]解决方案使用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插件非常相似的解决方案。

#2


31  

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

这里有一个简单的CSS only解决方案(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>

#3


14  

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

CSS3引入了相对于viewport(本例中的窗口)进行测量的新单元。这是vh和vw,分别测量视场高度和宽度。这里有一个简单的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.

需要注意的是,只有在页面上没有其他元素贡献高度时,它才会工作。

#4


11  

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.

玩小提琴。

#5


1  

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>

#6


1  

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
  • 宽度:100vw -图片宽度将为视场端口的100%
  • 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

    最大高度:100vw -如果图像的高度超过了视图端口,它将会被降低以适应屏幕,因此由于以下属性,图像的宽度将会降低

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

    对象拟合:包含——被替换的内容被缩放以保持其纵横比,同时在元素的内容框中进行拟合

    Note: object-fit is fully supported only since IE 16.0

    注意:对象匹配只有在ie16.0之后才被完全支持

#7


0  

width: 100%;
overflow: hidden;

I believe that should do the trick.

我相信这是有道理的。

#8


0  

html, body{width: 99%; height: 99%; overflow: hidden}
img.fit{width: 100%; height: 100%;}

Or maybe check this out: http://css-tricks.com/how-to-resizeable-background-image/

或者看看这个:http://css- phs.com/how to resizeable- backgroundimage/

#9


0  

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(int 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%的图像宽度,因为总是需要考虑一些填充。