Alfonso_MA
Alfonso_MA

Reputation: 555

Resize image in grid to fit div to smaller size

I am trying to build a header with 3 columns. One image in each column. I need the images to resize to fit the height of the header.

My images have 100px x 100px resolution.

So with heights higher than 100px the resizing is working fine:

enter image description here

But with with heights smaller than 100px the image is not resizing.

enter image description here

Here is my HTML

<body>
    <div id="header">
        <div class="headergridelement"><img alt="" src="file:///C:/.../info100x100.jpg"></div>
        <div class="headergridelement"><img alt="" src="file:///C:/.../info100x100.jpg"></div>
        <div class="headergridelement"><img alt="" src="file:///C:/.../info100x100.jpg"></div>
    </div>
</body>

and here is the css I am using.

#header {
    display: grid;
    grid-template-columns: auto auto auto;
    position: fixed;
    width: 100%;
    text-align: center;
    height:100%;
}

#header .headergridelement {
   background-color: rgba(255, 255, 255, 1);
}

#header img {
    height:100%;
}


body {
    margin-top: 0px;
    margin-left: 0px;
}

What property I am missing?

Upvotes: 1

Views: 636

Answers (1)

Henfs
Henfs

Reputation: 5411

You can add object-fit: cover and then specify the max-height you need, that is 100% in this case.
So, it prevents the image from overflowing the #header element.

#header img {
    height: 100%;
    object-fit: cover;
    max-height: 100%;
}

You can take a look about object-fit here at MDN docs.

Update: solution 2

The code above works fine in Chrome browser, but doesn't work in Firefox.
A solution for Firefox would be to use position: relative in the parent div and position: absolute in the image. In addition, set height: 100% and position and margin to center the image.

#header .headergridelement {
   background-color: rgba(255, 255, 255, 1);
   position: relative;
}
#header img {
  position: absolute;
  height: 100%;
  left: 0;
  right: 0;
  margin: 0 auto;
}

Upvotes: 1

Related Questions