CSS: set the image to its smaller side

I am trying to create an icon container that will display any image size (long or wide).

The image should correspond to the container with its smaller side, while additional functions will be located outside the container. Before applying overflow: hidden, it should work as follows.

enter image description here

This seems to be pretty easy to do with js, but I'm curious to find a css solution.

<div class="container"> <img src="test.png"/> </div> .container { width: 30px; height: 30px; } .container img { position: relative; left: 50%; top: 50%; transform: translateY(-50%) translateX(-50%); } 
+6
source share
3 answers

This is a rather difficult task if you do not want to resort to CSS backgrounds using background-size:cover (although this is really not a bad solution) due to one key factor: landscape and portrait images. Unable to determine image orientation in CSS. This is a problem because you cannot just set height and width (or max-height and max-width ) to 100% and expect it to work. This will distort the image and lose the aspect ratio. I suggest in this case to use some javascript to distinguish between the two. This is sad, but necessary if you want to achieve this effect with HTML img elements (again, not the only solution. Background images are still viable).

Here is what I came up with to achieve this effect:

 var images = document.querySelectorAll('.container img'); for(var i = 0, len = images.length; i < len; i++) { images[i].addEventListener('load', function() { this.className += (this.width > this.height) ? ' landscape' : ' portrait'; }); } 
 .container { position: relative; width: 50px; height: 50px; margin: 3em auto; } .container:after { content: ''; position: absolute; width: 100%; height: 100%; left: 0; top: 0; border: 2px solid; box-sizing: border-box; } .container img { position: absolute; max-width: 100%; max-height: 100%; top: 50%; left: 50%; transform: translate(-50%, -50%); padding: 2px; box-sizing: border-box; } .container img.landscape { max-width: none; } .container img.portrait { max-height: none; } 
 <div class="container"> <img src="//placehold.it/200x300"/> </div> <div class="container"> <img src="//placehold.it/300x200"/> </div> <div class="container"> <img src="//placehold.it/200x200"/> </div> <div class="container"> <img src="//placehold.it/500x100"/> </div> 
+1
source

use these css properties

  .container img { height:100%; width:100%; } 
0
source

https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit

it turns out another way to do this.

 <img style='height: 100%, width: 100%, object-fit: cover'/> 

will do the job. This is CSS3.

Fiddle: http://jsfiddle.net/mbHB4/3/

0
source

Source: https://habr.com/ru/post/983082/


All Articles