sdvnksv
sdvnksv

Reputation: 9668

Generate a square thumbnail image regardless the image ratio

I am looking for a CSS only solution to generate a square thumbnail regardless an image ratio:

.thumbnail {
  width: 100px;
  height: 100px;
  overflow: hidden;
}
img {
  width: 100%;
  height: auto;
}

The example above will create a square thumbnail only if the image is a portrait view, landscape view images won't cover the full height of the thumbnail.

Is there a CSS only solution (besides setting it as a background image) to do this?

Upvotes: 1

Views: 3032

Answers (1)

Turnip
Turnip

Reputation: 36642

The only way (I think) of doing this without the usual background-image / background-size method is to use object-fit. Though it won't work in IE:

.thumbnail {
  width: 150px;
  height: 150px;
  overflow: hidden;
}

img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* for demo only...*/
div {
  margin-bottom: 15px;
}
.noscale {
  width: auto;
  height: auto;
}
<div class="thumbnail">
  <img src="//placekitten.com/200/300">
</div>

<div class="thumbnail">
  <img src="//placekitten.com/300/200">
</div>

<h4>
Images for reference:
</h4>
<img src="//placekitten.com/200/300" class="noscale">
<img src="//placekitten.com/300/200" class="noscale">

Browser Support #object-fit

Upvotes: 2

Related Questions