Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image to be max-width: 100%, height: auto but height not less than XX without scretching

Tags:

html

css

image

There is an image inside a container. Image takes 100% of its width and height is auto. But I want to set the height to be at least XXX pixels so when I resize container's width, no matter what, the image stays at least certain height and width increases in order to keep proportions. The problem with my current approach below is that image dimensions get skewed after container is resized.

<div class="imageHelper">
    <img src="http://farm8.staticflickr.com/7230/7218149614_e0ba252f73_b.jpg" alt="image" />
</div>

.imageHelper {
    position: relative;
    width: 100%;
    height: 600px;
    overflow: hidden;
}

.imageHelper img {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 100%;
    max-width: 100%;
    width:auto\9;
    height: auto;
    min-height: 600px;
    -ms-transform: translate(-50%, -50%);
    -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
}

I have setup Fiddle ( http://jsfiddle.net/5JY8c/1/ ) which you can try to resize and check out why current approach is not working.

like image 570
Karolis Ramanauskas Avatar asked Mar 03 '14 18:03

Karolis Ramanauskas


People also ask

What is the difference between height auto and height 100%?

height: 100% gives the element 100% height of its parent container. height: auto means the element height will depend upon the height of its children.

How do you fix the width and height of an image?

The height and width of an image can be set using height and width attribute. The height and width can be set in terms of pixels. The <img> height attribute is used to set the height of the image in pixels. The <img> width attribute is used to set the width of the image in pixels.


2 Answers

This article might help in general:

http://www.creativebloq.com/css3/control-image-aspect-ratios-css3-2122968

And this part in particular:

object-fit: cover;
overflow: hidden;

Works with CSS3.

UPD: As Mark suggested, this approach only works in modern browsers: http://caniuse.com/object-fit

like image 88
dnl-blkv Avatar answered Sep 22 '22 11:09

dnl-blkv


Is this what you are after?

.imageHelper img {
  position: absolute;
  top: 0%;
  left: 0%;
  max-width: 100%;
  max-height: 100%;
}

See example here

You can change both the height and width of the container.. and the image will always remain proportional.

like image 20
ekhaled Avatar answered Sep 23 '22 11:09

ekhaled