使图像宽度为父div的100%,但不要超过它自己的宽度

[英]Make an image width 100% of parent div, but not bigger than its own width


I’m trying to get an image (dynamically placed, with no restrictions on dimensions) to be as wide as its parent div, but only as long as that width isn’t wider than its own width at 100%. I’ve tried this, to no avail:

我试着让一个图像(动态放置,不受尺寸限制)和它的父div一样宽,但是只要这个宽度不超过它自己的宽度100%。我试过了,但没有效果:

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

Many of these images are way wider than their parent div, which is why I’d like them to resize accordingly, but when a small image pops in there and gets scaled up beyond its normal dimensions, it really looks terrible. Is there any way of doing this?

这些图像中的许多比它们的父div宽得多,这就是为什么我想让它们相应地调整大小,但是当一个小的图像跳出来,并且放大到超出正常尺寸时,它看起来真的很糟糕。有什么办法吗?

5 个解决方案

#1


155  

Just specify max-width: 100% alone, that should do it.

只需要指定max-width: 100%就可以了。

#2


7  

Found this post on a Google search, and it solved my issue thanks to @jwal reply, but I made one addition to his solution.

在谷歌搜索中找到这篇文章,通过@jwal的回复解决了我的问题,但是我在他的解决方案中增加了一个。

img.content.x700 {
  width: auto !important; /*override the width below*/
  width: 100%;
  max-width: 678px;
  float: left;
  clear: both;
}

With the above I changed the max-width to the dimensions of the content container that my image is in. In this case it is: container width - padding - boarder = max width

通过上面的操作,我将最大宽度更改为图像所在的内容容器的尺寸。在这种情况下,它是:容器宽度-填充-边框=最大宽度

This way my image won't break out of the containing div, and I can still float the image within the content div.

这样,我的图像就不会跳出包含的div,我仍然可以在内容div中浮动图像。

I've tested in IE 9, FireFox 18.0.2 and Chrome 25.0.1364.97, Safari iOS and seems to work.

我已经在IE 9、FireFox 18.0.2和Chrome 25.0.1364.97、Safari iOS上测试过了,看起来还不错。

Additional: I tested this on an image 1024px wide displayed at 678px (the max width), and an image 500px wide displayed at 500px (width of the image).

另外:我在图片1024px宽678px(最大宽度)和图片500px宽500px(图片宽度)上进行了测试。

#3


2  

Setting a width of 100% is the full width of the div it's in, not the original full-sized image. There is no way to do that without JavaScript or some other scripting language that can measure the image. If you can have a fixed width or fixed height of the div (like 200px wide) then it shouldn't be too hard to give the image a range to fill. But if you put a 20x20 pixel image in a 200x300 pixel box it will still be distorted.

设置100%的宽度是它所在的div的全宽度,而不是原始的全尺寸图像。没有JavaScript或其他脚本语言可以测量图像,就无法做到这一点。如果div具有固定的宽度或固定的高度(比如200px宽),那么给图像填充一个范围应该不会太难。但是如果你把一个20x20像素的图像放在一个200x300像素的盒子里,它仍然会被扭曲。

#4


0  

If the image is smaller than parent...

如果图像比父图像小…

.img_100 {
  width: 100%;
}

#5


-1  

I would use the property display: table-cell

我将使用属性display: table-cell

Here is the link

这里是链接


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2010/08/11/323a8fd1f0c6ca9e3075e41ac013f263.html



 
  © 2014-2022 ITdaan.com 联系我们: