Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Contain image size with parent <div>

I´ve been trying to keep my images next to each other on the same line, and just crop them to a smaller size if needed. Why doesn't object-fit work ?

HTML:

<div class="gallery">
  <div class="inner"><img src="images/image1.jpg"></div>
  <div class="inner"><img src="images/image2.jpg"></div>
  <div class="inner"><img src="images/image3.jpg"></div>
</div>

CSS:

.gallery{
  width: 1000px;
  height: 300px;
  display: flex;
}

.inner{
   width: 333px;
   height: 300px;
}

.inner img{
   object-fit: contain;
}
like image 930
Jonas.D Avatar asked Aug 01 '18 19:08

Jonas.D


People also ask

How do you make a picture full height of a parent?

The image is set as a BLOCK element, min-width/height both set to 100% means to resize the image no matter of its size to be the minimum of 100% of it's parent. min is the key. If by min-height, the image height exceeded the parent's height, no problem.

How do I make Div fit to parent DIV?

Method 1: First method is to simply assign 100% width and 100% height to the child div so that it will take all available space of the parent div. Consider this HTML for demonstration: HTML.


1 Answers

You should set the width and height on the img in order to use it with object-fit. And it looks like object-fit: cover; might be what you're after.

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

Full snippet:

.gallery {
  width: 1000px;
  height: 300px;
  display: flex;
}

.inner {
  flex: 0 0 33.333333%;
  /*or flex: 1; */
  /*or width: 33.333333%; */
  height: 100%;
}

img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
<div class="gallery">
  <div class="inner"><img src="https://picsum.photos/300/300"></div>
  <div class="inner"><img src="https://picsum.photos/400/600"></div>
  <div class="inner"><img src="https://picsum.photos/600/400"></div>
</div>
like image 130
Stickers Avatar answered Sep 28 '22 21:09

Stickers