Alexandre Krabbe
Alexandre Krabbe

Reputation: 771

How to make images fill table cells while keeping aspect ratio?

What I'm trying to do is fill table cells with random sized images, but I want the cell to keep a height of 200px, the width must be automatically adjusted to fill the whole table width, that is td{width: 100%; height: 200px;}. And the images should fit inside the cells in a manner that they fill the whole cell without distortion, they can be cropped if needed.

I was looking for a solution on the forums and found that I should set the size of my table cell to whatever dimensions I want, and then set the image inside it to img{with: 100%; height: auto;} It makes sense to me but unfortunately it doesn't work. I put a JSFiddle together to show what is happening: JSFiddle

Any help is appreciated.

Upvotes: 1

Views: 3700

Answers (1)

Ariel Weinberger
Ariel Weinberger

Reputation: 2291

Either force the table cells to have the same ratio as the image (@Terry) or use the image as a background for the cell.

CSS:

td {
    background-image: url('path-to-image');
    background-size: cover;
    background-position: center;
}

JSFiddle: https://jsfiddle.net/1myu255g/ Please forgive me for not using all images, but I am sure you got the point :).

Upvotes: 4

Related Questions