How to adjust picture in container

Asked

Viewed 1,194 times

0

I have a 1220x780 image and I want to put it in a 341x192 container, how do I make it appear adjusted, centered, in "miniature", I’m using

 max-width: ;
 max-height:;
 width: auto;
 height: auto;

But it doesn’t fit horizontally

1 answer

1


let’s take for example this image.:

It’s 512 x 512, so let’s put it inside a 256 x 128 container

.box {
  float: left;
  width: 256px;
  height: 128px;
  margin: 10px 5px;
  border-radius: 5px;
  box-shadow: 0px 0px 10px black;
  overflow: hidden;
}

.bg {
  background-image: url('https://image.flaticon.com/icons/png/512/944/944939.png');
  background-position: center;
  background-size: cover;
  width: 100%;
  height: 100%;
}

.img {
  object-fit: cover;
  width: 100%;
  height: 100%;
}
<div class="box">
  <div class="bg"></div>
</div>

<div class="box">
  <img src="https://image.flaticon.com/icons/png/512/944/944939.png" class="img" />
</div>

That is, we can make this positioning using the background-size: cover; background-position: center; for background images or object-fit: cover; for images.

now if you want to keep the image aspect ratio and not cut it, you can use the contain instead of cover.

.box {
  float: left;
  width: 256px;
  height: 128px;
  margin: 5px 5px;
  border-radius: 5px;
  box-shadow: 0px 0px 10px black;
  overflow: hidden;
}

.bg {
  background-image: url('https://image.flaticon.com/icons/png/512/944/944939.png');
  background-position: center;
  background-repeat: no-repeat;
  background-size: contain;
  width: 100%;
  height: 100%;
}

.img {
  object-fit: contain;
  width: 100%;
  height: 100%;
}
<div class="box">
  <div class="bg"></div>
</div>

<div class="box">
  <img src="https://image.flaticon.com/icons/png/512/944/944939.png" class="img" />
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.