Search code examples
htmlcssimageaspect-ratio

how to center absolute positioned <img> in <div> but keep original aspect ratio


I have this image, with this CSS:

.containerImg {
    height: 420px;
    margin-top: 0;
    position: relative;
    width: 100%;
}

.img {
    margin: 0 auto;
    position: absolute;          /*unfortunately i can’t remove the position:absolute*/
}

And the markup:

<div class="containerImg">
<img class="img" alt="" src="img//section_es_2442.jpg">
<div class="info">
        …
          </div>
<div class="clear"></div>
</div>

And I post it so you can see that the img is not the only thing in the .container

So behavior is that image should use all .container dimensions and crop de image but keep the original ratio, images are 1600x500 (3,2:1)

So, how can i achieve this?


Solution

  • If I were you, I would to use background-image instead of img using this code:

    .containerImg {
        height: 420px;
        margin-top: 0;
        position: relative;
        width: 100%;
    }
    
    .img {
        margin: 0; 
        /*position: absolute;    I'll remove this */
        height: 420px;
        width: 100%; /*or use pixels*/
        background: transparent url('') no-repeat center top;
        overflow: hidden; /* not sure about you really need this */
    }
    

    with :

    <div class="containerImg">
      <div class="img" style="background-image: url('img/section_es_2442.jpg')"></div>
      <div class="info">
            …
      </div>
      <div class="clear"></div>
    </div>
    

    The idea is you have a div like view port, and the image with same ratio and size will be background, if the image is bigger, the additional size will "like" cropped :)