chuckfinley
chuckfinley

Reputation: 2595

CSS: keep aspect ratio when rendering an image

a simple CSS problem:

Some HTML:

<div class="gallery-item" style="height: 232px;">
                    <img src="/media/animals/images/african-buffalo.jpg" alt="African Buffalo ">

                    <div class="gallery-item-caption">
                        <a href="/animals/african-buffalo" title="African Buffalo ">African Buffalo </a>
                    </div>
</div>

Some CSS:

.gallery-item {
float: left;
padding: 15px 15px 15px 15px;
margin: 15px;
background-color: #ececec;
}

View:

enter image description here

Upvotes: 0

Views: 1545

Answers (1)

Valentin
Valentin

Reputation: 2858

Instead of img you can set the background-image on divs. If you find that images don't fit well in a square (very wide images), you can change to background-size:cover. Idea taken from here, working example here

CSS

.gallery-item{
    width:50px;
    height:50px;
    border:solid 1px #000;
    margin:10px;
    background:url('http://lorempixel.com/100/200') center center no-repeat;
    background-size:100%;
}

Upvotes: 1

Related Questions