Search code examples
htmlcsscentering

Centering a bigger image in a DIV


I'm trying to center (&crop) a big image in a smaller div. Here is how I want it to look like: enter image description here

The image is simply centered to the div; it doens't matter how bigger or smaller the image is.

Any ideas?


Solution

  • You can use transform combined with position:absolute to place it

    <div class="container">
        <img src="http://lorempixel.com/500/400/sports/1/" />
    </div>
    

    and

    .container {
        width:200px;
        height:200px;
        position:relative;
    }
    .container img {
        /*position it starting at the center*/
        position:absolute;
        left:50%;
        top:50%;
    
        /*move it back by 50% of the image*/
        transform-origin: 50% 50%;
        transform:translate(-50%,-50%);
    }
    

    Demo at http://jsfiddle.net/4nH3A/1/


    if you want to crop it as well, just add overflow:hidden to the div as well.

    Demo at http://jsfiddle.net/4nH3A/2/