0

I am getting an image inside div with unknown width and height. I want to have an image with maximal width or height - something like background-size: contain.

Here is my source code:

CSS

.box {
    display: block;
    position: fixed;
    height: auto;
    bottom: 0;
    top: 0;
    left: 0;
    right: 0;
    margin-top: 50px;
    margin-bottom: 50px;
    margin-right: 80px;
    margin-left: 80px;
    background-color: white;
    border: solid 2px blue;
}

.box img {
    max-width: 100%;
    max-height: 100%; 
}

HTML

<div class="box">
<img src="myimage.jpg">
</div>

Max-width is working well, but max-height does not work.

Shoe
  • 74,840
  • 36
  • 166
  • 272
Tomas Nekvinda
  • 524
  • 1
  • 5
  • 15
  • 1
    I don't fully understand what you'd like to achieve. Do you want the image to always be inside the div? Then just give overflow: hidden; to the .box class. Also, remove the height: auto; from the .box class. – pentzzsolt Feb 02 '13 at 09:56
  • 2
    You can set only width OR height. If you set the width, the height will be adjusted accordingly. The browser cannot change the `widthxheight` ratio of an image. If an image is actually 200x800 and you set the width to be 100, the height would automatically be 400. – Adil Malik Feb 02 '13 at 09:56
  • possible duplicate of [CSS: 100% width or height while keeping aspect ratio?](http://stackoverflow.com/questions/3751565/css-100-width-or-height-while-keeping-aspect-ratio) – easwee Feb 02 '13 at 09:58
  • I dont´t want to set the width of image. I want to have the image always inside the div without crop like using background-size: contain for background-image. – Tomas Nekvinda Feb 02 '13 at 10:05
  • @easwee .. I think this question is different. ncq doesn't want to keep the espect ratio. – Adil Malik Feb 02 '13 at 10:05
  • @ncq .. can you please share a screenshot of what you are seeing on your browser right now? That might give us better idea of what you want. – Adil Malik Feb 02 '13 at 10:06
  • Here is a live [show](http://vyzkum.neqindi.cz/obrazek.html) – Tomas Nekvinda Feb 02 '13 at 10:11
  • As @Adil Malik said. Try this: adjust only the height of your image to 100%, leave the width alone to be auto and set max-width to 100%. – pentzzsolt Feb 02 '13 at 10:12
  • It is unfortunately changing the aspect ratio of image. – Tomas Nekvinda Feb 02 '13 at 10:16

1 Answers1

1

What you want is not possible with only CSS.

There are JS plug-ins out there to make this for you. Look for imgscale it's a jQuery plugin for this matter and, although it needs some adjustments, have a great base to begin with.

here is a link of one copy I've modified: http://www.dtavares.com/imgscale/js/jquey.imgscale.js

You can call it as:

 $(".someConainer img").imgscale({parent: '.someConainer', scale: 'fit', center: true, fade: 0});
Ricardo Souza
  • 16,030
  • 6
  • 37
  • 69