Adam
Adam

Reputation: 1985

Fill an image in a square container while keeping aspect ratio

I am trying to make a grid of images in CSS, out of random sized images that are not square. Does anyone have a solution to filling all the space inside a fixed sized div with the image ?

See my example (blue is a fixed size div and red in the image inside it:

Image Example

Upvotes: 3

Views: 3087

Answers (6)

Sakai
Sakai

Reputation: 637

You could use just css for it but js can help, here follow my simple code.

    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">

<html>
<head>
    <title></title>
    <style type="text/css">
        div.image-box{display:block;position:relative;overflow:hidden;width:200px;border:1px solid #ccc;padding:0;height:200px;}
        div.image-box img{width:100%;height:auto;margin:0; padding:0;margin-bottom:-4px;position:absolute;top:0;left:0;}
        div.image-box.horizontal img{height:100%;width:auto;left:50%;}
        div.image-box.vertical img{height:auto;width:100%;top:50%;}
    </style>
</head>

<body>
    <div class="image-box"><img src="https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcS08-IWtcbvcehgeszlD2nI6s-OAungNCsLNIc-f3QjIOkvOq8abg" alt=""></div>
    <div class="image-box"><img src="http://1.bp.blogspot.com/_e-y-Rrz58H4/TUS4qRlRUrI/AAAAAAAABQo/H322eTHRB2s/s1600/Man_Face.jpg" alt=""></div>

    <script type="text/javascript" src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $('.image-box').each(function(){
                if($(this).find('img').height() > $(this).find('img').width()){
                    $(this).addClass('vertical');
                    $(this).find('img').css('margin-top','-'+$(this).find('img').height()/2+'px');
                }else{
                    $(this).addClass('horizontal');
                    $(this).find('img').css('margin-left','-'+$(this).find('img').width()/2+'px');
                }
            });
        });

    </script>
</body>
</html>

Hope that helps

Upvotes: 0

agrm
agrm

Reputation: 3852

Seeing as you've tagged the question with jQuery i'll take the liberty to suggest you write a small jQuery plugin for this. Here's the JSFiddle demo.

// Define plugin 'containImg'
$.fn.containImg = function(){
    this.each(function(){
        // Set variables
        var $t = $(this),
            $p = $t.parent('div'),
            pw = $p.width(),
            ph = $p.height(),
            // Figure if width or height should be 100%
            iw = ( pw / ph >= 1 ) ? 'auto' : '100%',
            ih = ( iw == 'auto' ) ? '100%' : 'auto';
        // Set dimensions
        $t.css({
            'width': iw,
            'height': ih
        });
    });
}

// Call plugin
$('img').containImg();

The basic logic is if the image has a horizontally stretched parent div, you'll need to set height:100% to fill the height, and width:auto to maintain the aspect ratio. If the parent div shape is vertical, you'll have to reverse this.

If anyone has views on how to improve the code I'm up for suggestions!

Upvotes: 0

Shailesh
Shailesh

Reputation: 337

You can try below css for image tag of your fixed div in this solution one condition you have to follow which is, your images size should be larger then your div i.e if your div will be 100px then minimum image size should be 100px or more then that :

div > img {
 width:100%;
 overflow:hidden;
} 

Upvotes: 0

Silvertiger
Silvertiger

Reputation: 1680

I have some code that does this and allows you to set the required sizes ...

<?PHP
function imageResize($image,$maxwidth,$maxheight) {
    $imgData = getimagesize("img/profiles/".$image);    
    $width  = $imgData[0];
    $height = $imgData[1];
    // takes the larger size of the width and height and applies the
    // formula accordingly...this is so this script will work
    // dynamically with any size image
    // First we'll scale down the width since it's the larger of the tw values
    if ($width > $maxwidth) {
        $percentage = ($maxwidth / $width);
        $width = round($width * $percentage);
        $height = round($height * $percentage);
    }
    // Next we'll scale down the height since it's the larger of the tw values
    if ($height > $maxheight) {
        $percentage = ($maxheight / $height);
        $width = round($width * $percentage);
        $height = round($height * $percentage);
    }
    $topMargin = ($maxheight-$height)/2;
    $topMargin .= "px";
    //returns the new sizes in html image tag format...
    // this is so you can plug this function inside an image tag and just get the results
    return "width=\"$width\" height=\"$height\" style=\"margin-top:$topMargin px;\"";
}
?>

and then include the following:

<div id="profile-picture">
    <img src="img/profiles/<?PHP echo $profileImg; ?>" <?PHP echo imageResize($profileImg,238,232); ?> />
</div>

Not sure if that's helpful .. but it worked for me.

Upvotes: 0

pbjork
pbjork

Reputation: 616

You can use the css, background-size: cover;

<style>
    .img1 {
        background-image: url(microsoft-logo.png);
    }
    .img2 {
        background-image: url(google-icon.png);
    }
    .img3 {
        background-image: url(Azend_Loggo.png);
    }
    .img-cover {
        width: 50px;
        height: 50px;
        background-size: cover;
        background-position: center;
        background-repeat: no-repeat;
    }
</style>

<div class="img-cover img1">

</div>
<div class="img-cover img2">

</div>
<div class="img-cover img3">

</div>

Upvotes: 5

Jonathan
Jonathan

Reputation: 9151

Use this CSS rule:

background-size: cover;
background-position: center;

DEMO

Upvotes: 3

Related Questions