Images in Divs

Asked

Viewed 99 times

3

I have a question about divs with imagens in the case, the doubt is as follows:

  • If I have a div, with 400x400, how do I make an image with 200x400 (or other resolution) fit by occupying the total size of the div, without distorting the imagem, and without using the background of css

For example:

*the first imagem is how the end result would be, the way it is said, the second is how it normally looks, the imagem whole is placed in the div, always leaving white space, both vertical, as horizontal, the image should be adjusted according to the size of the div.

inserir a descrição da imagem aqui

2 answers

2


The image I will use for testing has the 500x375 resolution so I would do it as follows:

img {
  width: 400px;
  height: 400px;
  object-fit: cover;
}
<img src="http://dicasdeboleiro.com.br/wp-content/uploads/2013/06/Dicas-de-dribles-de-futebol-2.jpg">

Observe the property object-fit: cover that gives this effect on the image as if it were a background-size: cover see more in:
https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit

Note. Without the property object-fit: cover the image is distorted.

  • Problem is supported browsers. But it is a good option when everyone else stops using IE.

  • @IE and EDGE are really a problem as always kkk but this property using prefixes is already supported by 91.5% of browsers in Brazil according

  • Chic 10 even. I will start using.

1

You can use the overflow: hidden the element surrounding the image so that the image stays within the established limits. And in the image you can subtract the margins 50% (half of 100%), above and below.

.imagem-1 {
  width: 400px;
  height: 400px;
  overflow: hidden;
}
.imagem-1 img {
  width: 100%;
  margin-top: -50%;
  margin-bottom: -50%;
}
<div class="imagem-1">
  <img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=200x400&w=200&h=400">
</div>

Browser other questions tagged

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