使圖像寬度為父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 联系我们: