Frnak
Frnak

Reputation: 6802

How to keep an image centered if the parent is smaller?

i currently try to a response design. I need to keep the image centered while the parent div gets smaller.

See image as explanation:enter image description here

I dont want to use it as background. The following code will always place it at the top left of the div box

<div id="img_wrap">
    <img src="test.png" id="img" />
</div>

<style type="text/css">
    #img_wrap {
        overflow: hidden;
        text-align: center;
    }
</style>

Upvotes: 2

Views: 89

Answers (4)

Adarsh Gowda K R
Adarsh Gowda K R

Reputation: 951

For making the image center

<div id="img_wrap">
    <img src="http://placehold.it/350x150" id="img" />
</div>


<style type="text/css">
       #img_wrap{  
         position: relative;
        width: 200px;
         height:150px;/*give the image height*/
        background: red;
        overflow:hidden;
       display: inline-block;
    }

    #img{
      position: absolute;
     left: 50%;
     transform: translateX(-50%);
   }
    </style>

Here is the demo http://jsfiddle.net/adarshkr/p1p100h7/1/

Upvotes: 0

Sauryabhatt
Sauryabhatt

Reputation: 269

If Old browser compatibility is not an issue you can use following

#img_wrap img
{
   display:flex;
   -ms-flex-pack:stretch;
   -webkit-box-pack:stretch;
   justify-content:center;
}

Upvotes: 0

OpherV
OpherV

Reputation: 6937

Here's an example

#img_wrap{
  position: relative;
  overflow: hidden;

  /* arbitrary container size */
  width: 7rem; 
  height: 16rem;
}

#img{
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translateX(-50%) translateY(-50%);
}

The trick is that the image is absolutely placed at the center, 50% of its parent container width, then shifted left 50% of it's own width with the transform.

Upvotes: 2

Adarsh Gowda K R
Adarsh Gowda K R

Reputation: 951

Here is the solution, to make image responsive..

<div id="img_wrap">
    <img src="test.png" id="img" />
</div>

<style type="text/css">


      #img_wrap{
        position:relative
        }
    #img_wrap img{
       max-width:100%;
       height:auto;
       margin:0 auto;
       display:block;


    }
</style>

Hope it helps...

Upvotes: -1

Related Questions