Search code examples
cssimagepercentagecentering

Centering images within a flexible container


Been playing around for a while now with trying to get this to work so I have set up a CodePen and hope you guys can help:

CODEPEN

I need the height and width of .container to be specified with percentages rather than static pixel widths to fit my design and keep it all fluid and responsive.

In the pen remove the pixel dimensions set on .container and you'll see what happens.

Is there a way this can be done?


Solution

  • For modern browsers you can use absolute positioning and transform to position the image

    .container
      width: 50% 
      height: 50%
    
      background-color: #ebebeb
      position: relative
    
    img
      position: absolute
      left: 50%
      top: 50%
      transform: translate(-50%, -50%)
    

    Demo at http://codepen.io/gpetrioli/pen/KnHod