1
votes

How can one without using JS achieve these effects all together with any image (both large and small, with arbitrary size ratio) and any container sizes (but fixed).

  1. image is centered both horizontally and vertically with respect to container
  2. image aspect ratio is preserved
  3. if image width/height is larger than that of container, than image height is 100% of container, and image is cropped by width. If width/height of image is smaller than that of container, than image width is 100% of container, and image is cropped by height.

I know about solution using background image. Please offer only solutions with <img>

3

3 Answers

2
votes

It's as simple as:

background-size: cover;
background-position: center center;

Obviously this only works for background images, for actual image elements you might want to look into CSS3 flexbox.

0
votes

You cna wrap it in a container like this and control its size with min values, although if your screen is smaller than the image width it will just crop everywhere.

img {
    position: absolute;
    left: 0;
    left: calc(50%);
    top: 0;
    top: calc(50%);
    transform: translate(-50%,-50%);
    min-width: 100%;
    min-height: 100%;
}

You can add media queries to solve the size issue, though:

@media all and (orientation:landscape){
    width: 100vmax;
    min-width: 0; min-height: 0;
}
@media all and (orientation:portrait){
    height: 100vmax;
    min-width: 0; min-height: 0;
}

However, easer might be the background-size: cover property and assign it as a background:

<div style="background-image: url(url/to/image.ext);"></div>
div {
    background-size: cover;
    background-position: 50% 50%;
}
0
votes

I tried before on multiple projects, and the best thing I could get is choosing the preferred dimension, risking the other. I was never able to make it adjust to both situations, the cropping could happen only in one dimension. Here is an example (height will get cropped if too large, but width will always be 100%). I'm interested in finding a way out of this.

.container {
 overflow: hidden;
 width: 400px;
 height: 300px;
 position:relative
}

img {
 position: absolute;
 top: 0;
 right: 0;
 bottom: 0;
 left: 0;
 margin: auto; /* this centers image inside */
 width: 100%; /* this is to shrink the images of large width */
}