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

前端 未结 9 670
暗喜
暗喜 2020-11-30 19:53

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

9条回答
  •  南方客
    南方客 (楼主)
    2020-11-30 20:39

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

    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.

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

    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).

提交回复
热议问题