2015-06-05 56 views
5

我想调整基于屏幕尺寸的图像,但我不希望这样的图像超过其实际工作时的像素屏幕太大。 到目前为止,我成功地做到这自动调整图像以适合比例,但不舒展

<div align="center" style="position:static; height: 100%; width: 100%; top:0;left 0;"> 
<img src="myImg.png" style="width: 80%"> 
</div> 

这保持我想要的比例,但是当屏幕太大,也拉伸了图像。我不想那样。

回答

10

的响应图像的CSS如下:

max-width: 100%; 
    height: auto; 

这将使图像缩小与它的容器的大小,不超过该图像的自然宽度。但是,使用width: 100%;将强制图像与其容器一样宽,无论图像的实际大小如何。

其他一些注意事项:

  • align="center"已被弃用。你应该使用CSS来对齐内容,所以text-align: center;
  • 使用position: static;是不必要的,因为它是用于位置属性的默认值。我唯一能想到的地方就是你需要重写一些其他的css。
  • 除非你是绝对定位你的div(你不是),那么top: 0; left: 0;什么都不会做。

没有看到你的代码的其余部分,我想这将是你试图完成什么是最好的解决办法:

<div style="text-align: center;"> 
     <img src="myImg.png" style="max-width: 100%; height: auto;" alt="FYI, image alt text is required" /> 
    </div> 
1

如果您还设置了max-width属性,它会限制图像可以是多大得到。像这样:

<div align="center" style="position:static; height: 100%; width: 100%; top:0;left 0;"> 
    <img src="myImg.png" style="width: 80%; max-width: 300px;"> 
</div> 

可以使这个max-width任何你想要的大小,只要不超过图像的实际宽度。高度也可以。

-7
class="img-thumbnail" 

可能是解决方案。

+0

现在“img-fluid”在Bootstrap 4中 – Eduardo